package cn.lili.modules.member.serviceimpl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.context.ThreadContextHolder;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.SwitchEnum;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.RocketmqCustomProperties;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.security.token.Token;
import cn.lili.common.sensitive.SensitiveWordsFilter;
import cn.lili.common.utils.*;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.audit.entity.dos.AuditPartner;
import cn.lili.modules.audit.enums.AuditPartnerStatus;
import cn.lili.modules.audit.mapper.AuditPartnerMapper;
import cn.lili.modules.connect.config.ConnectAuthEnum;
import cn.lili.modules.connect.entity.Connect;
import cn.lili.modules.connect.entity.dto.ConnectAuthUser;
import cn.lili.modules.connect.service.ConnectService;
import cn.lili.modules.member.aop.annotation.PointLogPoint;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.dto.*;
import cn.lili.modules.member.entity.enums.PartnerStatusEnum;
import cn.lili.modules.member.entity.enums.PointTypeEnum;
import cn.lili.modules.member.entity.vo.*;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.*;
import cn.lili.modules.member.token.MemberTokenGenerate;
import cn.lili.modules.member.token.StoreTokenGenerate;
import cn.lili.modules.message.entity.dos.RollMessage;
import cn.lili.modules.message.mapper.RollMessageMapper;
import cn.lili.modules.permission.entity.dos.*;
import cn.lili.modules.permission.mapper.RoleMapper;
import cn.lili.modules.permission.service.*;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.entity.dos.RegionDetail;
import cn.lili.modules.system.entity.vo.RegionDetailVO;
import cn.lili.modules.system.mapper.RegionDetailMapper;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.entity.vo.RechargeVO;
import cn.lili.modules.wallet.mapper.RechargeMapper;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.whitebar.entity.dos.RateSetting;
import cn.lili.modules.whitebar.mapper.RateSettingMapper;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.rocketmq.RocketmqSendCallbackBuilder;
import cn.lili.rocketmq.tags.MemberTagsEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 会员接口业务层实现
 *
 * @author Chopper
 * @since 2021-03-29 14:10:16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    /**
     * 会员token
     */
    @Autowired
    private MemberTokenGenerate memberTokenGenerate;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private StoreUserService storeUserService;

    /**
     * 菜单角色
     */
    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 商家token
     */
    @Autowired
    private StoreTokenGenerate storeTokenGenerate;
    /**
     * 联合登录
     */
    @Autowired
    private ConnectService connectService;
    /**
     * 店铺
     */
    @Autowired
    private StoreService storeService;
    /**
     * RocketMQ 配置
     */
    @Autowired
    private RocketmqCustomProperties rocketmqCustomProperties;
    /**
     * RocketMQ
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 缓存
     */
    @Autowired
    private Cache cache;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private RollMessageMapper rollMessageMapper;
    /**
     * 合伙人
     */
    @Autowired
    private PartnerService partnerService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private PartnerMapper partnerMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RateSettingMapper rateSettingMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private EextensionService eextensionService;
    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private AuditPartnerMapper auditPartnerMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private RegionDetailMapper regionDetailMapper;

    @Autowired
    private AccessTokenService accessTokenService;

    @Override
    public Member findByUsername(String userName) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Member findByUsernameXcx(String userName) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        queryWrapper.eq("have_store", true); // 是否开通店铺1,true有0,false没有
        queryWrapper.eq("type", 1); // 当前用户状态1商家2小程序用户
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Role> findRoleById(String id) {
        return this.baseMapper.findRoleById(id);
    }

    @Override
    public Member getUserInfo() {
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser != null) {
            return this.findByUsername(tokenUser.getUsername());
        }
        throw new ServiceException(ResultCode.USER_NOT_LOGIN);
    }

    @Override
    public MemberVO getUserInfos(String owner, String username, String exCode) {
        MemberVO vo = getUserInfos(owner, username);
        eextensionService.bindTempEx(vo.getId(), exCode);
        return vo;
    }

    @Override
    public MemberVO getUserInfos(String owner, String username) {
        AuthUser tokenUser = UserContext.getCurrentUser();
        String userName = "";
        if (StringUtils.isNotEmpty(username)) {
            userName = username;
        } else {
            userName = tokenUser.getUsername();
        }
        if (tokenUser != null) {
            // 绑定临时推广码

            QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("m.username", userName);
            // queryWrapper.and(wrapper -> wrapper.isNull("g.owner").or().like("g.owner",
            // owner));
            queryWrapper.orderByAsc("c.LEVEL");
            queryWrapper.last("limit 1");
            return this.baseMapper.findByUsername(queryWrapper);
        }
        throw new ServiceException(ResultCode.USER_NOT_LOGIN);
    }

    @Override
    public MemberVO getUserInfosByMemberId(String owner, String memberName) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("m.username", memberName);
        queryWrapper.orderByAsc("c.LEVEL");
        queryWrapper.last("limit 1");
        return this.baseMapper.findByUsername(queryWrapper);
    }

    @Override
    public MemberVO findByPhone(QueryWrapper<Member> queryWrapper) {
        return this.baseMapper.findByUsername(queryWrapper);
    }

    @Override
    public boolean findByMobile(String uuid, String mobile) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Member member = this.baseMapper.selectOne(queryWrapper);
        if (member == null) {
            throw new ServiceException(ResultCode.USER_NOT_PHONE);
        }
        cache.put(CachePrefix.FIND_MOBILE + uuid, mobile, 300L);

        return true;
    }

    @Override
    public Token usernameLogin(String username, String password) {
        Member member = this.findMember(username);
        // 判断用户是否存在
        if (member == null || !member.getDisabled()) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        // 判断密码是否输入正确
        if (!new BCryptPasswordEncoder().matches(password, member.getPassword())) {
            throw new ServiceException(ResultCode.USER_PASSWORD_ERROR);
        }
        loginBindUser(member);
        return memberTokenGenerate.createToken(member.getUsername(), false);
    }

    @Override
    public Token usernameStoreLogin(String username, String password) {
        StoreUser storeUser = this.findStoreUser(username);
        if (storeUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
            // Member member = this.findMember(username);
            // //判断用户是否存在
            // if (member == null || !member.getDisabled()) {
            // throw new ServiceException(ResultCode.USER_NOT_EXIST);
            // }
            // //判断密码是否输入正确
            // if (!new BCryptPasswordEncoder().matches(password, member.getPassword())) {
            // throw new ServiceException(ResultCode.USER_PASSWORD_ERROR);
            // }
            // //对店铺状态的判定处理
            // if (Boolean.TRUE.equals(member.getHaveStore())) {
            // Store store = storeService.getById(member.getStoreId());
            // if (!store.getStoreDisable().equals(StoreStatusEnum.OPEN.name())) {
            // throw new ServiceException(ResultCode.STORE_CLOSE_ERROR);
            // }
            // } else {
            // throw new ServiceException(ResultCode.USER_NOT_EXIST);
            // }
            // return storeTokenGenerate.createToken(member.getUsername(), false);
        } else {
            // 判断密码是否输入正确
            if (!new BCryptPasswordEncoder().matches(password, storeUser.getPassword())) {
                throw new ServiceException(ResultCode.USER_PASSWORD_ERROR);
            }
            // 对店铺状态的判定处理
            Store store = storeService.getById(storeUser.getStoreId());
            if (store == null) {
                throw new ServiceException(ResultCode.STORE_NOT_OPEN);
            }
            if (!store.getStoreDisable().equals(StoreStatusEnum.OPEN.name())) {
                throw new ServiceException(ResultCode.STORE_CLOSE_ERROR);
            }
            if (!storeUser.getStatus()) {
                throw new ServiceException(ResultCode.STORE_CLOSE_ERROR_Disable);
            }
            return storeTokenGenerate.createToken(storeUser.getUsername(), false);
        }
    }

    /**
     * 传递手机号或者用户名
     *
     * @param userName 手机号或者用户名
     * @return 会员信息
     */
    private StoreUser findStoreUser(String userName) {
        QueryWrapper<StoreUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName).or().eq("mobile", userName);
        return storeUserService.getOne(queryWrapper);
    }

    /**
     * 传递手机号或者用户名
     *
     * @param userName 手机号或者用户名
     * @return 会员信息
     */
    private Member findMember(String userName) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName).or().eq("mobile", userName);
        return this.getOne(queryWrapper);
    }

    @Override
    public Token autoRegister(ConnectAuthUser authUser) {

        if (CharSequenceUtil.isEmpty(authUser.getNickname())) {
            authUser.setNickname("临时昵称");
        }
        if (CharSequenceUtil.isEmpty(authUser.getAvatar())) {
            authUser.setAvatar("https://i.loli.net/2020/11/19/LyN6JF7zZRskdIe.png");
        }
        try {
            String username = UuidUtils.getUUID();
            Member member = new Member(username, UuidUtils.getUUID(), authUser.getAvatar(), authUser.getNickname(),
                    authUser.getGender() != null ? Convert.toInt(authUser.getGender().getCode()) : 0);
            // 保存会员
            this.save(member);
            Member loadMember = this.findByUsername(username);
            // 绑定登录方式
            loginBindUser(loadMember, authUser.getUuid(), authUser.getSource());
            return memberTokenGenerate.createToken(username, false);
        } catch (ServiceException e) {
            log.error("自动注册服务泡出异常：", e);
            throw e;
        } catch (Exception e) {
            log.error("自动注册异常：", e);
            throw new ServiceException(ResultCode.USER_AUTO_REGISTER_ERROR);
        }
    }

    @Override
    public Token autoRegister() {
        ConnectAuthUser connectAuthUser = this.checkConnectUser();
        return this.autoRegister(connectAuthUser);
    }

    @Override
    public Token refreshToken(String refreshToken) {
        return memberTokenGenerate.refreshToken(refreshToken);
    }

    @Override
    public Token refreshStoreToken(String refreshToken) {
        return storeTokenGenerate.refreshToken(refreshToken);
    }

    @Override
    public Token mobilePhoneLogin(String mobilePhone) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobilePhone);
        Member member = this.baseMapper.selectOne(queryWrapper);
        // 如果手机号不存在则自动注册用户
        if (member == null) {
            member = new Member(mobilePhone, UuidUtils.getUUID(), mobilePhone);
            // 保存会员
            this.save(member);
            String destination = rocketmqCustomProperties.getMemberTopic() + ":"
                    + MemberTagsEnum.MEMBER_REGISTER.name();
            rocketMQTemplate.asyncSend(destination, member, RocketmqSendCallbackBuilder.commonCallback());
        }
        loginBindUser(member);
        return memberTokenGenerate.createToken(member.getUsername(), false);
    }

    @Override
    public Member editOwn(MemberEditDTO memberEditDTO) {
        // 查询会员信息
        Member member = this.findByUsername(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername());
        // 传递修改会员信息
        BeanUtil.copyProperties(memberEditDTO, member);
        // 修改会员
        this.updateById(member);
        return member;
    }

    @Override
    public Member modifyPass(String newPassword, String confirmPassword) {
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        Member member = this.getById(tokenUser.getId());

        if (StringUtils.isNotBlank(newPassword)) {
            // 判断旧密码输入是否正确
            if (!new BCryptPasswordEncoder().matches(newPassword, confirmPassword)) {
                throw new ServiceException(ResultCode.USER_OLD_PASSWORD_ERROR);
            }
        }
        // 修改会员密码
        LambdaUpdateWrapper<Member> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(Member::getId, member.getId());
        lambdaUpdateWrapper.set(Member::getPaymentPassword, new BCryptPasswordEncoder().encode(newPassword));
        this.update(lambdaUpdateWrapper);

        Member memberNew = this.getById(tokenUser.getId());
        return memberNew;
    }

    @Override
    public StoreUser modifyLoginPass(String oldPassword, String newPassword) {
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        StoreUser byId = storeUserService.getById(tokenUser.getId());
        if (StringUtils.isNotBlank(oldPassword)) {
            // 判断旧密码输入是否正确
            if (!new BCryptPasswordEncoder().matches(oldPassword, byId.getPassword())) {
                throw new ServiceException(ResultCode.USER_OLD_PASSWORD_ERROR);
            }
        }
        // 修改会员密码
        LambdaUpdateWrapper<StoreUser> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(StoreUser::getId, byId.getId());
        lambdaUpdateWrapper.set(StoreUser::getPassword, new BCryptPasswordEncoder().encode(newPassword));
        storeUserService.update(lambdaUpdateWrapper);
        StoreUser StoreUserNew = storeUserService.getById(tokenUser.getId());
        return StoreUserNew;
    }

    @Override
    public Token register(String userName, String password, String mobilePhone) {
        // 检测会员信息
        checkMember(userName, mobilePhone);
        // 设置会员信息
        Member member = new Member(userName, new BCryptPasswordEncoder().encode(password), mobilePhone);
        // 注册成功后用户自动登录
        if (this.save(member)) {
            Token token = memberTokenGenerate.createToken(member.getUsername(), false);
            String destination = rocketmqCustomProperties.getMemberTopic() + ":"
                    + MemberTagsEnum.MEMBER_REGISTER.name();
            rocketMQTemplate.asyncSend(destination, member, RocketmqSendCallbackBuilder.commonCallback());
            return token;
        }
        return null;
    }

    @Override
    public boolean changeMobile(String mobile) {
        AuthUser tokenUser = Objects.requireNonNull(UserContext.getCurrentUser());
        Member member = this.findByUsername(tokenUser.getUsername());

        // 判断是否用户登录并且会员ID为当前登录会员ID
        if (!Objects.equals(tokenUser.getId(), member.getId())) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        // 修改会员手机号
        LambdaUpdateWrapper<Member> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(Member::getId, member.getId());
        lambdaUpdateWrapper.set(Member::getMobile, mobile);
        return this.update(lambdaUpdateWrapper);
    }

    @Override
    public boolean resetByMobile(String uuid, String password) {
        String phone = cache.get(CachePrefix.FIND_MOBILE + uuid).toString();
        // 根据手机号获取会员判定是否存在此会员
        if (phone != null) {
            // 修改密码
            LambdaUpdateWrapper<Member> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
            lambdaUpdateWrapper.eq(Member::getMobile, phone);
            lambdaUpdateWrapper.set(Member::getPassword, new BCryptPasswordEncoder().encode(password));
            cache.remove(CachePrefix.FIND_MOBILE + uuid);
            return this.update(lambdaUpdateWrapper);
        } else {
            throw new ServiceException(ResultCode.USER_PHONE_NOT_EXIST);
        }

    }

    @Override
    public Member addMember(MemberAddDTO memberAddDTO) {

        // 检测会员信息
        checkMember(memberAddDTO.getUsername(), memberAddDTO.getMobile());
        // 添加会员
        Member member = new Member(memberAddDTO.getUsername(),
                new BCryptPasswordEncoder().encode(memberAddDTO.getPassword()), memberAddDTO.getMobile());
        member.setId(memberAddDTO.getMemberId());
        member.setHaveStore(true);
        member.setType(1);
        this.updateById(member);
        String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_REGISTER.name();
        rocketMQTemplate.asyncSend(destination, member, RocketmqSendCallbackBuilder.commonCallback());
        return member;
    }

    @Override
    public Member updateMember(ManagerMemberEditDTO managerMemberEditDTO) {
        // 判断是否用户登录并且会员ID为当前登录会员ID
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        // 过滤会员昵称敏感词
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(managerMemberEditDTO.getNickName())) {
            managerMemberEditDTO.setNickName(SensitiveWordsFilter.filter(managerMemberEditDTO.getNickName()));
        }
        // 如果密码不为空则加密密码
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(managerMemberEditDTO.getPassword())) {
            managerMemberEditDTO.setPassword(new BCryptPasswordEncoder().encode(managerMemberEditDTO.getPassword()));
        }
        // 查询会员信息
        Member member = this.findByUsername(managerMemberEditDTO.getUsername());
        // 传递修改会员信息
        BeanUtil.copyProperties(managerMemberEditDTO, member);
        this.updateById(member);
        return member;
    }

    @Override
    public Boolean updatePartner(List<String> id, Integer partnerState) {
        UpdateWrapper<Partner> updateWrapper = Wrappers.update();
        updateWrapper.set("partner_state", partnerState);
        updateWrapper.set("update_time", new Date());
        updateWrapper.in("member_id", id);
        return partnerService.update(updateWrapper);
    }

    @Override
    public IPage<MemberVO> getMemberPage(MemberSearchVO memberSearchVO, PageVO page) {

        QueryWrapper<Member> queryWrapper = Wrappers.query();
        // 获取区域下的所有地区
        if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
            List itemAdCod = regionService.getItemAdCod(memberSearchVO.getRegionId());
            queryWrapper.in("a.location", itemAdCod);
        }
        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("a.location", itemAdCod);
        }
        if (null != memberSearchVO.getType() && 0 != memberSearchVO.getType()) {
            // 查询用户类型
            queryWrapper.eq("a.type", memberSearchVO.getType());
        }
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "a.username",
                memberSearchVO.getUsername());
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getNickName()), "a.nick_name",
                memberSearchVO.getNickName());
        // 按照电话号码查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "a.mobile",
                memberSearchVO.getMobile());
        // 按照会员状态查询
        if (StringUtils.isNotEmpty(memberSearchVO.getDisabled())) {
            queryWrapper.eq("a.disabled", memberSearchVO.getDisabled().equals(SwitchEnum.OPEN.name()) ? 1 : 0);
        }
        queryWrapper.and(wrapper -> wrapper.isNull("b.grade_state").or().eq("b.grade_state", 0));
        queryWrapper.and(wrapper -> wrapper.isNull("b.delete_flag").or().eq("b.delete_flag", 0));
        // queryWrapper.and(wrapper ->
        // wrapper.isNull("e1.delete_flag").or().eq("e1.delete_flag", 0));
        queryWrapper.eq(null != memberSearchVO.getExtension(), "e1.extension", memberSearchVO.getExtension());
        queryWrapper.eq("a.delete_flag", 0);
        queryWrapper.orderByDesc("a.create_time");
        IPage<MemberVO> memberVOIPage;
        if (memberSearchVO.getType() == 1) {
            queryWrapper.eq("s.store_disable", "OPEN");
            memberVOIPage = baseMapper.pageByBMemberVO(PageUtil.initPage(page), queryWrapper);
        } else {
            // queryWrapper.isNull("p.id");
            queryWrapper.and(wrapper -> wrapper.isNull("b.owner").or().like("b.owner", "BUYER"));
            queryWrapper.and(wrapper -> wrapper.isNull("p.audit_state").or().ne("p.audit_state", "PASS"));
            memberVOIPage = this.baseMapper.pageByCMemberVO(PageUtil.initPage(page), queryWrapper);
        }
        // 根据ad_code查询区域
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
            MemberVO byMemberId = eextensionService.findByMemberId(item.getId());
            if (byMemberId != null) {
                item.setMobileExte(byMemberId.getMobile());// 获取推广人手机号
            }
            item.setRechargeMoney(
                    BigDecimal.valueOf(item.getRechargeMoney()).setScale(2, RoundingMode.DOWN).doubleValue());
            item.setPromoteMoney(
                    BigDecimal.valueOf(item.getPromoteMoney()).setScale(2, RoundingMode.DOWN).doubleValue());
            if (item.getSaleMoney() != null)
                item.setSaleMoney(BigDecimal.valueOf(item.getSaleMoney()).setScale(2, RoundingMode.DOWN).doubleValue());
        });
        return memberVOIPage;
    }

    @Override
    public List<MemberVO> getMemberList(MemberSearchVO memberSearchVO) {

        QueryWrapper<Member> queryWrapper = Wrappers.query();
        // 获取区域下的所有地区
        if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
            List itemAdCod = regionService.getItemAdCod(memberSearchVO.getRegionId());
            queryWrapper.in("a.location", itemAdCod);
        }
        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("a.location", itemAdCod);
        }
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "a.username",
                memberSearchVO.getUsername());
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getNickName()), "a.nick_name",
                memberSearchVO.getNickName());
        // 按照电话号码查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "a.mobile",
                memberSearchVO.getMobile());
        // 按照会员状态查询
        queryWrapper.eq("a.disabled", 1);
        queryWrapper.eq(null != memberSearchVO.getExtension(), "e1.extension", memberSearchVO.getExtension());
        queryWrapper.eq("a.delete_flag", 0);
        queryWrapper.orderByDesc("a.create_time");
        queryWrapper.and(wrapper -> wrapper.isNull("p.audit_state").or().ne("p.audit_state", "PASS"));
        List<MemberVO> memberVO = this.baseMapper.listByMember(queryWrapper);
        if (CollectionUtils.isNotEmpty(memberVO)) {
            // 根据ad_code查询区域
            memberVO.forEach(item -> {
                item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
//				MemberVO byMemberId = eextensionService.findByMemberId(item.getId());
//				if (byMemberId != null) {
//					item.setMobileExte(byMemberId.getMobile());// 获取推广人手机号
//				}
            });
        }
        return memberVO;
    }

    @Override
    public IPage<MemberVO> noPartnerMemberList(MemberSearchVO memberSearchVO, PageVO page) {

        QueryWrapper<Member> queryWrapper = Wrappers.query();
        // 获取区域下的所有地区
        if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
            List itemAdCod = regionService.getItemAdCod(memberSearchVO.getRegionId());
            queryWrapper.in("a.location", itemAdCod);
        }
        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("a.location", itemAdCod);
        }
        if (StringUtils.isNotEmpty(memberSearchVO.getPartnerId())) {
            queryWrapper.eq("a.partner_id", memberSearchVO.getPartnerId());
        }
        // 按照电话号码查询
        queryWrapper.eq(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "a.mobile",
                memberSearchVO.getMobile());
        //
        queryWrapper.eq("a.delete_flag", 0);
        queryWrapper.orderByDesc("a.create_time");
        queryWrapper.groupBy("a.id");
        queryWrapper.having("COUNT( b.id )=0");

        // 不同角色查询不同无上级会员的列表(天使>C端/事业>焕商/城市>所有)
        String roleType = memberSearchVO.getRoleType();
        if (StringUtils.equals(roleType, "ANGEL_PARTNER")) {// 天使合伙人
            queryWrapper.isNull("d.id");
        } else if (StringUtils.equals(roleType, "BUSINESS_PARTNER")) {// 事业合伙人
            queryWrapper.eq("a.have_store", "1");
        }

        IPage<MemberVO> memberVOIPage;
        memberVOIPage = this.baseMapper.noPartnerMemberList(PageUtil.initPage(page), queryWrapper);
        // 根据ad_code查询区域
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return memberVOIPage;
    }

    @Override
    public IPage<MemberVO> updatePartner(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        if (null != memberSearchVO.getType() && 0 != memberSearchVO.getType()) {
            // 查询用户类型
            queryWrapper.eq("m.type", memberSearchVO.getType());
        }
        // 推广人姓名
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getNameExte()), "m1.real_name", memberSearchVO.getNameExte());
        // 推广人电话
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getMobileExte()), "m1.mobile", memberSearchVO.getMobileExte());
        if (null != memberSearchVO.getPartnerType() && 4 == memberSearchVO.getPartnerType()) {
            // 查询合伙人类型
            List<Integer> partnerType = new ArrayList<>();
            partnerType.add(2);
            partnerType.add(3);
            queryWrapper.in("p.partner_type", partnerType);
        } else if (null != memberSearchVO.getPartnerType()) {
            queryWrapper.eq("p.partner_type", memberSearchVO.getPartnerType());
        }
        // 合伙人类型
        if (null != memberSearchVO.getRoleType() && StringUtils.isNotEmpty(memberSearchVO.getRoleType())) {
            if (StringUtils.equals(memberSearchVO.getRoleType(), "STORE")) {
                queryWrapper.eq("m.have_store", "1");
                queryWrapper.eq("lro.name", UserEnums.ANGEL_PARTNER.getRole());
                queryWrapper.in("ls.store_disable", StoreStatusEnum.OPEN.name(), StoreStatusEnum.CLOSED.name());
                queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getStoreName()), "ls.store_name",
                        memberSearchVO.getStoreName());
            } else {
                if (StringUtils.equals(memberSearchVO.getRoleType(), "ANGEL_PARTNER")) {
                    queryWrapper.eq("m.have_store", "0");
                }
                queryWrapper.eq("lro.name", UserEnums.valueOf(memberSearchVO.getRoleType()).getRole());
            }
        }

        if (StringUtils.isNotEmpty(memberSearchVO.getExtension())) {
            queryWrapper.eq("e1.extension", memberSearchVO.getExtension());
        } else {
            if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
                List list = regionService.getPartnerAdCode(memberSearchVO.getRegionId(), "4");
                queryWrapper.in(list != null && list.size() > 0, "m.location", list);

            }
        }
        // 店铺区域
        if (StringUtils.isNotEmpty(memberSearchVO.getStoreAddressPath())) {
            List list = regionService.getItemAdCod(memberSearchVO.getStoreAddressPath());
            queryWrapper.in(CollectionUtils.isNotEmpty(list), "ls.ad_code", list);
        }

        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("m.location", itemAdCod);
        }
        if (memberSearchVO.getBeginTime() != null && memberSearchVO.getEndTime() != null) {
            // queryWrapper.between("p.begin_time", memberSearchVO.getBeginTime(),
            // memberSearchVO.getEndTime());
            queryWrapper.le("DATE_FORMAT(p.begin_time,'%Y-%m-%d')",
                    DateUtil.toString(memberSearchVO.getEndTime(), "yyyy-MM-dd"));
            queryWrapper.ge("DATE_FORMAT(p.begin_time,'%Y-%m-%d')",
                    DateUtil.toString(memberSearchVO.getBeginTime(), "yyyy-MM-dd"));

        }
        queryWrapper.eq(null != memberSearchVO.getId(), "m.id", memberSearchVO.getId());
        // 会员禁用状态
        queryWrapper.eq(null != memberSearchVO.getDisabled(), "m.disabled", memberSearchVO.getDisabled());
        queryWrapper.eq(null != memberSearchVO.getExtension(), "e1.extension", memberSearchVO.getExtension());
        queryWrapper.eq(StringUtils.isNotEmpty(memberSearchVO.getRegion()), "p.region", memberSearchVO.getRegion());
        // 审核状态
        memberSearchVO.setAuditStates("PASS");
        if (StringUtils.isNotEmpty(memberSearchVO.getAuditStates())) {
            List list = Arrays.asList(memberSearchVO.getAuditStates().split(","));
            queryWrapper.in(list != null && list.size() > 0, "p.audit_state", list);
        }
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "m.username",
                memberSearchVO.getUsername());
        // 支付状态
        queryWrapper.and(qw -> qw.eq("p.pay_state", 1).or().isNull("p.pay_state"));
        // 禁用状态
        queryWrapper.eq("p.partner_state", 0);
        queryWrapper.eq("p.delete_flag", 0);
        queryWrapper.eq("m.delete_flag", 0);
        queryWrapper.groupBy("m.id");
        queryWrapper.orderByDesc("p.create_time");
        queryWrapper.eq(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "m.mobile",
                memberSearchVO.getMobile());
        long l = System.currentTimeMillis();
        log.info(l + "**********************************************************************************");
        IPage<MemberVO> memberVOIPage = this.baseMapper.updatePartner(PageUtil.initPage(page), queryWrapper);
        long l2 = System.currentTimeMillis();
        log.info(l2 + "**********************************************************************************");
        log.info(l2 - l + "**********************************************************************************");
        for (MemberVO m : memberVOIPage.getRecords()) {
            if (StringUtils.isNotEmpty(m.getLocation())) {
                m.setLocationName(regionService.getItemAdCodOrName(m.getLocation()));
            }

            QueryWrapper<Extension> wrapper = Wrappers.query();
            wrapper.eq("extension", m.getPromotionCode());
            wrapper.eq("delete_flag", 0);
            m.setQuantity(eextensionService.list(wrapper).size());//推广会员数

            // 钱包余额
            List<MemberWallet> memberWallet = memberWalletService.getMemberWalletById(m.getId());
            memberWallet.forEach(wallet -> {
                switch (wallet.getOwner()) {
                    case "SALE": // 销售钱包余额
                        m.setSaleMoney(wallet.getMemberWallet() != null ? wallet.getMemberWallet() : 0D);// 销售钱包余额
                        break;
                    case "PROMOTE": // 推广钱包余额
                        m.setPromoteMoney(wallet.getMemberWallet() != null ? wallet.getMemberWallet() : 0D); // 推广钱包余额
                        break;
                    case "RECHARGE":// 充值钱包余额
                        m.setRechargeMoney(wallet.getMemberWallet() != null ? wallet.getMemberWallet() : 0D);// 充值钱包余额
                        break;
                    case "PROMOTE_FW":// 推广会员费钱包余额
                        m.setPromoteFwMoney(wallet.getMemberWallet() != null ? wallet.getMemberWallet() : 0D); // 推广会员费钱包余额
                        break;
                    case "PROMOTE_HY":// 推广服务费钱包余额
                        m.setPromoteHyMoney(wallet.getMemberWallet() != null ? wallet.getMemberWallet() : 0D);// 推广服务费钱包余额
                        break;
                }
            });
            m.setAllMoney(CurrencyUtil.roundDown(
                    CurrencyUtil.add(
                            m.getSaleMoney(), m.getPromoteMoney(), m.getRechargeMoney(), m.getPromoteFwMoney(), m.getPromoteHyMoney()
                    ), 2));// 总余额
            m.setSaleMoney(CurrencyUtil.roundDown(m.getSaleMoney(), 2));// 销售钱包余额
            m.setPromoteMoney(CurrencyUtil.roundDown(m.getPromoteMoney(), 2)); // 推广钱包余额
            m.setRechargeMoney(CurrencyUtil.roundDown(m.getRechargeMoney(), 2));// 充值钱包余额
            m.setPromoteFwMoney(CurrencyUtil.roundDown(m.getPromoteFwMoney(), 2)); // 推广会员费钱包余额
            m.setPromoteHyMoney(CurrencyUtil.roundDown(m.getPromoteHyMoney(), 2));// 推广服务费钱包余额
            // 充值现金，焕呗
            Map<String, Object> allMoneyByMember = rechargeMapper.getAllMoneyByMember(m.getId());
            if (null != allMoneyByMember) {
                if (null != allMoneyByMember.get("yi_bei"))
                    m.setAllYiBeiMoney(Double.parseDouble(allMoneyByMember.get("yi_bei").toString()));
                else
                    m.setAllYiBeiMoney(0D);

                if (null != allMoneyByMember.get("recharge_money"))
                    m.setAllRechargeMoney(Double.parseDouble(allMoneyByMember.get("recharge_money").toString()));
                else
                    m.setAllRechargeMoney(0D);
            }
            // 会员身份
            GradeVO gradeVO = gradeService.findByGradeVO(m.getId());
            if(null != gradeVO){
                m.setGradeName(gradeVO.getName());
            }
        }
        return memberVOIPage;
    }

    @Override
    public MemberVO countPartner(MemberSearchVO memberSearchVO) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        if (null != memberSearchVO.getType() && 0 != memberSearchVO.getType()) {
            // 查询用户类型
            queryWrapper.eq("m.type", memberSearchVO.getType());
        }
        // 推广人姓名
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getNameExte()), "m1.real_name", memberSearchVO.getNameExte());
        // 推广人电话
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getMobileExte()), "m1.mobile", memberSearchVO.getMobileExte());
        if (null != memberSearchVO.getPartnerType() && 4 == memberSearchVO.getPartnerType()) {
            // 查询合伙人类型
            List<Integer> partnerType = new ArrayList<>();
            partnerType.add(2);
            partnerType.add(3);
            queryWrapper.in("p.partner_type", partnerType);
        } else if (null != memberSearchVO.getPartnerType()) {
            queryWrapper.eq("p.partner_type", memberSearchVO.getPartnerType());
        }
        // 合伙人类型
        if (null != memberSearchVO.getRoleType() && StringUtils.isNotEmpty(memberSearchVO.getRoleType())) {
            if (StringUtils.equals(memberSearchVO.getRoleType(), "STORE")) {
                queryWrapper.eq("m.have_store", "1");
                queryWrapper.eq("lro.name", UserEnums.ANGEL_PARTNER.getRole());
                queryWrapper.in("ls.store_disable", StoreStatusEnum.OPEN.name(), StoreStatusEnum.CLOSED.name());
                queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getStoreName()), "ls.store_name",
                        memberSearchVO.getStoreName());
            } else {
                if (StringUtils.equals(memberSearchVO.getRoleType(), "ANGEL_PARTNER")) {
                    queryWrapper.eq("m.have_store", "0");
                }
                queryWrapper.eq("lro.name", UserEnums.valueOf(memberSearchVO.getRoleType()).getRole());
            }
        }

        if (StringUtils.isNotEmpty(memberSearchVO.getExtension())) {
            queryWrapper.eq("e1.extension", memberSearchVO.getExtension());
        } else {
            if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
                List list = regionService.getPartnerAdCode(memberSearchVO.getRegionId(), "4");
                queryWrapper.in(list != null && list.size() > 0, "m.location", list);

            }
        }
        // 店铺区域
        if (StringUtils.isNotEmpty(memberSearchVO.getStoreAddressPath())) {
            List list = regionService.getItemAdCod(memberSearchVO.getStoreAddressPath());
            queryWrapper.in(CollectionUtils.isNotEmpty(list), "ls.ad_code", list);
        }

        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("m.location", itemAdCod);
        }
        if (memberSearchVO.getBeginTime() != null && memberSearchVO.getEndTime() != null) {
            // queryWrapper.between("p.begin_time", memberSearchVO.getBeginTime(),
            // memberSearchVO.getEndTime());
            queryWrapper.le("DATE_FORMAT(p.begin_time,'%Y-%m-%d')",
                    DateUtil.toString(memberSearchVO.getEndTime(), "yyyy-MM-dd"));
            queryWrapper.ge("DATE_FORMAT(p.begin_time,'%Y-%m-%d')",
                    DateUtil.toString(memberSearchVO.getBeginTime(), "yyyy-MM-dd"));

        }
        queryWrapper.eq(null != memberSearchVO.getId(), "m.id", memberSearchVO.getId());
        // 会员禁用状态
        queryWrapper.eq(null != memberSearchVO.getDisabled(), "m.disabled", memberSearchVO.getDisabled());
        queryWrapper.eq(null != memberSearchVO.getExtension(), "e1.extension", memberSearchVO.getExtension());
        queryWrapper.eq(StringUtils.isNotEmpty(memberSearchVO.getRegion()), "p.region", memberSearchVO.getRegion());
        // 审核状态
        memberSearchVO.setAuditStates("PASS");
        if (StringUtils.isNotEmpty(memberSearchVO.getAuditStates())) {
            List list = Arrays.asList(memberSearchVO.getAuditStates().split(","));
            queryWrapper.in(list != null && list.size() > 0, "p.audit_state", list);
        }
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "m.username",
                memberSearchVO.getUsername());
        // 支付状态
        queryWrapper.and(qw -> qw.eq("p.pay_state", 1).or().isNull("p.pay_state"));
        // 禁用状态
        queryWrapper.eq("p.partner_state", 0);
        queryWrapper.eq("p.delete_flag", 0);
        queryWrapper.eq("m.delete_flag", 0);
        queryWrapper.groupBy("m.id,m.promotion_code");
        queryWrapper.orderByDesc("p.create_time");
        queryWrapper.eq(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "m.mobile",
                memberSearchVO.getMobile());
        long l = System.currentTimeMillis();
        log.info(l + "**********************************************************************************");
        MemberVO memberVO = this.baseMapper.countPartner(queryWrapper);
        long l2 = System.currentTimeMillis();
        log.info(l2 + "**********************************************************************************");
        log.info(l2 - l + "**********************************************************************************");
        if (StringUtils.isNotEmpty(memberVO.getLocation()))
            memberVO.setLocationName(regionService.getItemAdCodOrName(memberVO.getLocation()));
        return memberVO;
    }

    @Override
    public IPage<MemberVO> getPartnerList(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        if (null != memberSearchVO.getType() && 0 != memberSearchVO.getType()) {
            // 查询用户类型
            queryWrapper.eq("m.type", memberSearchVO.getType());
        }
        // 根据code查询合伙人管理的区域Code
        if (StringUtils.isNotEmpty(memberSearchVO.getAdcode())) {
            List itemAdCod = regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4");
            queryWrapper.in("m.location", itemAdCod);
        }
        if (null != memberSearchVO.getPartnerType() && 4 == memberSearchVO.getPartnerType()) {
            // 查询合伙人类型
            List<Integer> partnerType = new ArrayList<>();
            partnerType.add(2);
            partnerType.add(3);
            queryWrapper.in("p.partner_type", partnerType);
        } else if (null != memberSearchVO.getPartnerType()) {
            queryWrapper.eq("p.partner_type", memberSearchVO.getPartnerType());
        }
        // 合伙人类型
        if (null != memberSearchVO.getRoleType()) {
            if (StringUtils.equals(memberSearchVO.getRoleType(), "STORE")) {
                queryWrapper.eq("m.have_store", "1");
                queryWrapper.eq("lro.name", UserEnums.ANGEL_PARTNER.getRole());
                queryWrapper.eq("ls.store_disable", StoreStatusEnum.OPEN.name());
            } else {
                if (StringUtils.equals(memberSearchVO.getRoleType(), "ANGEL_PARTNER")) {
                    queryWrapper.eq("m.have_store", "0");
                }
                queryWrapper.eq("lro.name", UserEnums.valueOf(memberSearchVO.getRoleType()).getRole());
            }
            queryWrapper.eq("p.delete_flag", "0");
        }
        if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
            List list = regionService.getItemAdCod(memberSearchVO.getRegionId());
            queryWrapper.in(list != null && list.size() > 0, "m.location", list);
        }
        queryWrapper.eq(null != memberSearchVO.getId(), "m.id", memberSearchVO.getId());
        // 合伙人状态
        queryWrapper.eq(null != memberSearchVO.getPartnerState(), "p.partner_state", memberSearchVO.getPartnerState());
        queryWrapper.eq(null != memberSearchVO.getExtension(), "e1.extension", memberSearchVO.getExtension());
        queryWrapper.eq(StringUtils.isNotEmpty(memberSearchVO.getRegion()), "p.region", memberSearchVO.getRegion());
        // 审核状态
        if (StringUtils.isNotEmpty(memberSearchVO.getAuditStates())) {
            List list = Arrays.asList(memberSearchVO.getAuditStates().split(","));
            queryWrapper.in(list != null && list.size() > 0, "p.audit_state", list);
        }

        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "username",
                memberSearchVO.getUsername());
        // queryWrapper.eq("p.delete_flag", 0);
        queryWrapper.eq("m.delete_flag", 0);
        queryWrapper.groupBy("p.id");
        queryWrapper.orderByDesc("p.create_time");
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "m.mobile",
                memberSearchVO.getMobile());
        IPage<MemberVO> memberVOIPage = this.baseMapper.getPartnerList(PageUtil.initPage(page), queryWrapper);
        for (MemberVO m : memberVOIPage.getRecords()) {
            if (StringUtils.isNotEmpty(m.getLocation()))
                m.setLocationName(regionService.getItemAdCodOrName(m.getLocation()));
        }
        return memberVOIPage;
    }

    @Override
    public IPage<MemberVO> updateAgent(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        if (null != memberSearchVO.getType() && 0 != memberSearchVO.getType()) {
            // 查询用户类型
            queryWrapper.eq("m.type", memberSearchVO.getType());
        }
        // 查询合伙人类型
        queryWrapper.eq("p.partner_type", 4);
        // 合伙人状态
        queryWrapper.eq(null != memberSearchVO.getPartnerState(), "p.partner_state", memberSearchVO.getPartnerState());
        queryWrapper.eq(null != memberSearchVO.getId(), "m.id", memberSearchVO.getId());
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "username",
                memberSearchVO.getUsername());
        queryWrapper.eq("p.delete_flag", 0);
        queryWrapper.groupBy("m.id,m.promotion_code");
        queryWrapper.orderByDesc("p.create_time");
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "mobile",
                memberSearchVO.getMobile());
        return this.baseMapper.updatePartner(PageUtil.initPage(page), queryWrapper);
    }

    @Override
    @PointLogPoint
    public Boolean updateMemberPoint(Long point, String type, String memberId, String content) {
        // 获取当前会员信息
        Member member = this.getById(memberId);
        if (member != null) {
            // 积分变动后的会员积分
            long currentPoint;
            // 会员总获得积分
            long totalPoint = member.getTotalPoint();
            // 如果增加积分
            if (type.equals(PointTypeEnum.INCREASE.name())) {
                currentPoint = member.getPoint() + point;
                // 如果是增加积分 需要增加总获得积分
                totalPoint = totalPoint + point;
            }
            // 否则扣除积分
            else {
                currentPoint = member.getPoint() - point < 0 ? 0 : member.getPoint() - point;
            }
            member.setPoint(currentPoint);
            member.setTotalPoint(totalPoint);
            boolean result = this.updateById(member);
            if (result) {
                // 发送会员消息
                MemberPointMessage memberPointMessage = new MemberPointMessage();
                memberPointMessage.setPoint(point);
                memberPointMessage.setType(type);
                memberPointMessage.setMemberId(memberId);
                String destination = rocketmqCustomProperties.getMemberTopic() + ":"
                        + MemberTagsEnum.MEMBER_POINT_CHANGE.name();
                rocketMQTemplate.asyncSend(destination, memberPointMessage,
                        RocketmqSendCallbackBuilder.commonCallback());
                return true;
            }
            return false;

        }
        throw new ServiceException(ResultCode.USER_NOT_EXIST);
    }

    @Override
    public Boolean updateMemberStatus(List<String> memberIds, Boolean status) {
        UpdateWrapper<Member> updateWrapper = Wrappers.update();
        updateWrapper.set("disabled", status);
        updateWrapper.set("disable_time", new Date()); // 禁用时间
        updateWrapper.in("id", memberIds);
        return this.update(updateWrapper);
    }

    /**
     * 根据手机号获取会员
     *
     * @param mobilePhone 手机号
     * @return 会员
     */
    private Member findByPhone(String mobilePhone) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobilePhone);
        queryWrapper.eq("have_store", true); // 是否开通店铺1,true有0,false没有
        queryWrapper.eq("type", 1); // 当前用户状态1商家2小程序用户
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * 获取cookie中的联合登录对象
     *
     * @param uuid uuid
     * @param type 状态
     * @return cookie中的联合登录对象
     */
    private ConnectAuthUser getConnectAuthUser(String uuid, String type) {
        Object context = cache.get(ConnectService.cacheKey(type, uuid));
        if (context != null) {
            return (ConnectAuthUser) context;
        }
        return null;
    }

    /**
     * 成功登录，则检测cookie中的信息，进行会员绑定
     *
     * @param member  会员
     * @param unionId unionId
     * @param type    状态
     */
    private void loginBindUser(Member member, String unionId, String type) {
        Connect connect = connectService
                .queryConnect(ConnectQueryDTO.builder().unionId(unionId).unionType(type).build());
        if (connect == null) {
            connect = new Connect(member.getId(), unionId, type);
            connectService.save(connect);
        }
    }

    /**
     * 成功登录，则检测cookie中的信息，进行会员绑定
     *
     * @param member 会员
     */
    private void loginBindUser(Member member) {
        // 获取cookie存储的信息
        String uuid = CookieUtil.getCookie(ConnectService.CONNECT_COOKIE, ThreadContextHolder.getHttpRequest());
        String connectType = CookieUtil.getCookie(ConnectService.CONNECT_TYPE, ThreadContextHolder.getHttpRequest());
        // 如果联合登陆存储了信息
        if (CharSequenceUtil.isNotEmpty(uuid) && CharSequenceUtil.isNotEmpty(connectType)) {
            try {
                // 获取信息
                ConnectAuthUser connectAuthUser = getConnectAuthUser(uuid, connectType);
                if (connectAuthUser == null) {
                    return;
                }
                Connect connect = connectService.queryConnect(
                        ConnectQueryDTO.builder().unionId(connectAuthUser.getUuid()).unionType(connectType).build());
                if (connect == null) {
                    connect = new Connect(member.getId(), connectAuthUser.getUuid(), connectType);
                    connectService.save(connect);
                }
            } catch (ServiceException e) {
                throw e;
            } catch (Exception e) {
                log.error("绑定第三方联合登陆失败：", e);
            } finally {
                // 联合登陆成功与否，都清除掉cookie中的信息
                CookieUtil.delCookie(ConnectService.CONNECT_COOKIE, ThreadContextHolder.getHttpResponse());
                CookieUtil.delCookie(ConnectService.CONNECT_TYPE, ThreadContextHolder.getHttpResponse());
            }
        }

    }

    /**
     * 检测是否可以绑定第三方联合登陆 返回null原因 包含原因1：redis中已经没有联合登陆信息 2：已绑定其他账号
     *
     * @return 返回对象则代表可以进行绑定第三方会员，返回null则表示联合登陆无法继续
     */
    private ConnectAuthUser checkConnectUser() {
        // 获取cookie存储的信息
        String uuid = CookieUtil.getCookie(ConnectService.CONNECT_COOKIE, ThreadContextHolder.getHttpRequest());
        String connectType = CookieUtil.getCookie(ConnectService.CONNECT_TYPE, ThreadContextHolder.getHttpRequest());

        // 如果联合登陆存储了信息
        if (CharSequenceUtil.isNotEmpty(uuid) && CharSequenceUtil.isNotEmpty(connectType)) {
            // 枚举 联合登陆类型获取
            ConnectAuthEnum authInterface = ConnectAuthEnum.valueOf(connectType);

            ConnectAuthUser connectAuthUser = getConnectAuthUser(uuid, connectType);
            if (connectAuthUser == null) {
                throw new ServiceException(ResultCode.USER_OVERDUE_CONNECT_ERROR);
            }
            // 检测是否已经绑定过用户
            Connect connect = connectService.queryConnect(
                    ConnectQueryDTO.builder().unionType(connectType).unionId(connectAuthUser.getUuid()).build());
            // 没有关联则返回true，表示可以继续绑定
            if (connect == null) {
                connectAuthUser.setConnectEnum(authInterface);
                return connectAuthUser;
            } else {
                throw new ServiceException(ResultCode.USER_CONNECT_BANDING_ERROR);
            }
        } else {
            throw new ServiceException(ResultCode.USER_CONNECT_NOT_EXIST_ERROR);
        }
    }

    @Override
    public long getMemberNum(MemberSearchVO memberSearchVO) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getUsername()), "username",
                memberSearchVO.getUsername());
        // 按照电话号码查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "mobile",
                memberSearchVO.getMobile());
        // 按照状态查询
        queryWrapper.eq(CharSequenceUtil.isNotBlank(memberSearchVO.getDisabled()), "disabled",
                memberSearchVO.getDisabled().equals(SwitchEnum.OPEN.name()) ? 1 : 0);
        queryWrapper.orderByDesc("create_time");
        return this.count(queryWrapper);
    }

    /**
     * 获取指定会员数据
     *
     * @param columns   指定获取的列
     * @param memberIds 会员ids
     * @return 指定会员数据
     */
    @Override
    public List<Map<String, Object>> listFieldsByMemberIds(String columns, List<String> memberIds) {
        return this.listMaps(new QueryWrapper<Member>().select(columns).in(memberIds != null && !memberIds.isEmpty(),
                "id", memberIds));
    }

    /**
     * 登出
     */
    @Override
    public void logout(UserEnums userEnums) {
        String currentUserToken = UserContext.getCurrentUserToken();
        if (CharSequenceUtil.isNotEmpty(currentUserToken)) {
            cache.remove(CachePrefix.ACCESS_TOKEN.getPrefix(userEnums) + currentUserToken);
            accessTokenService.removeByAccessToken(currentUserToken);
        }
    }

    /**
     * 获取所有会员的手机号
     *
     * @return 所有会员的手机号
     */
    @Override
    public List<String> getAllMemberMobile() {
        return this.baseMapper.getAllMemberMobile();
    }

    @Override
    public void cleanMember() {
        baseMapper.cleanMember();
    }

    /**
     * 检测会员
     *
     * @param userName    会员名称
     * @param mobilePhone 手机号
     */
    private void checkMember(String userName, String mobilePhone) {
        // 判断用户名是否存在
        if (findByUsername(userName) != null) {
            throw new ServiceException(ResultCode.USER_NAME_YES);
        }
        // 判断手机号是否存在
        if (findByPhone(mobilePhone) != null) {
            throw new ServiceException(ResultCode.USER_NAME_YES);
        }
    }

    @Override
    public IPage<MemberStoreVO> getmemSto(MemberStoreVO memberStoreVO, PageVO page) {
        QueryWrapper<MemberStoreVO> queryWrapper = Wrappers.query();
        queryWrapper.eq("a.type", 1); // 用户类型 1 商家 2 小程序用户
        // 店铺名称
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberStoreVO.getStoreName()), "b.store_name",
                memberStoreVO.getStoreName());
        queryWrapper.eq("a.delete_flag", 0); // 删除标志 true/false 删除/未删除
        queryWrapper.eq("a.have_store", 1); // 是否开店 1是 0没有
        queryWrapper.eq("b.store_disable", 0); // 店铺状态
        queryWrapper.orderByDesc("a.create_time");
        return this.baseMapper.getmemSto(PageUtil.initPage(page), queryWrapper);
    }

    @Override
    public MemberPartnerVO getPartner() {
        Member member = this.getUserInfo();

        MemberPartnerVO memberPartnerVO = new MemberPartnerVO();
        memberPartnerVO.setId(member.getId());
        memberPartnerVO.setNickName(member.getNickName());
        memberPartnerVO.setMobile(member.getMobile());
        memberPartnerVO.setRealName(member.getRealName());
        memberPartnerVO.setLinkMobile(member.getLinkMobile());

        QueryWrapper<Partner> queryWrapper = new QueryWrapper<Partner>().eq("member_id", member.getId())
                .in("partner_type", 1, 2, 4).eq("partner_state", "0").eq("delete_flag", "0");

        List<Partner> partnerList = partnerMapper.selectList(queryWrapper);

        if (!partnerList.isEmpty()) {
            Partner partner = partnerList.get(0);
            memberPartnerVO.setPartnerType(partner.getPartnerType());
            memberPartnerVO.setPartnerState(partner.getPartnerState());
            memberPartnerVO.setAuditState(partner.getAuditState());
            memberPartnerVO.setAuditRemark(partner.getAuditRemark());
            memberPartnerVO.setPayState(partner.getPayState());
            memberPartnerVO.setRegion(partner.getRegion());
            memberPartnerVO.setRemark(partner.getRemark());
            // String roleId = partner.getRoleId();
            if (StringUtils.isNotEmpty(partner.getSn())) {
                // RateSetting rateSetting = getRateSettingByRoleId(roleId);
                // memberPartnerVO.setPartnerPrice(rateSetting.getPartnerPrice());

                QueryWrapper<Recharge> wrapper = new QueryWrapper<Recharge>();
                wrapper.eq("recharge_sn", partner.getSn());
                List<Recharge> recharges = rechargeMapper.selectList(wrapper);
                if (null != recharges && recharges.size() > 0) {
                    for (Recharge recharge : recharges) {
                        if ("WECHAT".equals(recharge.getRechargeWay())) {
                            memberPartnerVO.setPrice(recharge.getPrice());
                            memberPartnerVO.setPayTime(recharge.getPayTime());
                            // }else{
                            memberPartnerVO.setHbPrice(recharge.getRechargeMoney());
                        }
                    }
                }
            }
        }

        return memberPartnerVO;
    }

    @Override
    public void addPartner(MemberPartnerVO memberPartner) {
        Member member = new Member();
        member.setId(UserContext.getCurrentUser().getId());
        member.setRealName(memberPartner.getRealName());
        member.setLinkMobile(memberPartner.getLinkMobile());
        member.setIdCardNumber(memberPartner.getIdCardNumber());
        this.baseMapper.updateById(member);

        // Integer partnerType = memberPartner.getPartnerType();
        // Role role = getRoleByType(partnerType);
        // String roleId = role.getId();
        // RateSetting rateSetting = getRateSettingByRoleId(roleId);

        Partner partner = new Partner();

        // List<SysDictItemVO> allValue =
        // SysDictUtils.getAllValue(DictCodeEnum.PARTNER_PRICE.dictCode());
        // if (CollectionUtils.isNotEmpty(allValue)) {
        // for (SysDictItemVO sysDictItemVO : allValue) {
        // if
        // (memberPartner.getPartnerPrice().compareTo(Double.parseDouble(sysDictItemVO.getItemValue()))
        // == 0) {
        QueryWrapper queryWrapper = new QueryWrapper();
        Partner partner1 = new Partner();
        QueryWrapper partnerW = new QueryWrapper();
        partnerW.eq("member_id", UserContext.getCurrentUser().getId());
        if (memberPartner.getPartnerType() == 4) {
            partner.setPartnerType(4);
            queryWrapper.eq("name", "代理商");
            queryWrapper.eq("parent_id", 0);
            Role role = roleMapper.selectOne(queryWrapper);
            partner.setRoleId(role.getId());
            partnerW.eq("partner_type", 4);
            partnerW.last("limit 1");
            partner1 = this.partnerMapper.selectOne(partnerW);
            if (ObjectUtils.isNotEmpty(partner1)) {
                partner.setCode(partner1.getCode());
                partner.setPrefix(partner1.getPrefix());
            } else {
                QueryWrapper partnerQ = new QueryWrapper();
                partnerQ.eq("partner_type", 4);
                partnerQ.orderByDesc("create_time");
                partnerQ.last("limit 1");
                Partner partner2 = this.partnerMapper.selectOne(partnerQ);
                partner.setCode(partner2.getCode() + 1);
                partner.setPrefix("BHSQ-CSHHR01-");
            }
        } else if (memberPartner.getPartnerType() == 1) {
            queryWrapper.eq("name", "事业合伙人");
            queryWrapper.eq("parent_id", 0);
            Role role = roleMapper.selectOne(queryWrapper);
            partner.setRoleId(role.getId());
            partner.setPartnerType(1);
            partnerW.eq("partner_type", 1);
            partnerW.last("limit 1");
            partner1 = this.partnerMapper.selectOne(partnerW);
            if (ObjectUtils.isNotEmpty(partner1)) {
                partner.setCode(partner1.getCode());
                partner.setPrefix(partner1.getPrefix());
            } else {
                QueryWrapper partnerQ = new QueryWrapper();
                partnerQ.eq("partner_type", 1);
                partnerQ.orderByDesc("create_time");
                partnerQ.last("limit 1");
                Partner partner2 = this.partnerMapper.selectOne(partnerQ);
                partner.setCode(partner2.getCode() + 1);
                partner.setPrefix("BHSQ-SYHHR02-");
            }
        } else if (memberPartner.getPartnerType() == 2) {
            queryWrapper.eq("name", "天使合伙人");
            queryWrapper.eq("parent_id", 0);
            Role role = roleMapper.selectOne(queryWrapper);
            partner.setRoleId(role.getId());
            partner.setPartnerType(2);
            partnerW.eq("partner_type", 2);
            partnerW.last("limit 1");
            partner1 = this.partnerMapper.selectOne(partnerW);
            if (ObjectUtils.isNotEmpty(partner1)) {
                partner.setCode(partner1.getCode());
                partner.setPrefix(partner1.getPrefix());
            } else {
                QueryWrapper partnerQ = new QueryWrapper();
                partnerQ.eq("partner_type", 2);
                partnerQ.orderByDesc("create_time");
                partnerQ.last("limit 1");
                Partner partner2 = this.partnerMapper.selectOne(partnerQ);
                partner.setCode(partner2.getCode() + 1);
                partner.setPrefix("BHSQ-TSHHR03-");
            }
        } else if ("推广员".equals(memberPartner.getItemText())) {
            partner.setPartnerType(3);
        }
        // }
        // }
        // }
        partner.setMemberId(UserContext.getCurrentUser().getId());
        partner.setPartnerState(0);
        partner.setRegionId(memberPartner.getAdPath());
        partner.setRegion(memberPartner.getStoreAddressPath_path());
        partner.setRemark(memberPartner.getRemark());
        partner.setApplicationTime(new Date());
        partner.setRecommendPhone(memberPartner.getRecommendPhone());
        // 金额大于0才需要支付
        if (memberPartner.getPartnerPrice() > 0) {
            partner.setPayState(0);
            partner.setAuditState(PartnerStatusEnum.WAIT_SUBMIT.value());
            partner.setSn(memberPartner.getSn());
        } else {
            partner.setPayState(1);
            partner.setAuditState(PartnerStatusEnum.APPLYING.value());
        }

        partnerMapper.updateByMemberId(UserContext.getCurrentUser().getId());
        partnerMapper.insert(partner);
    }

    @Override
    public Boolean auditPartner(String id, String auditState, String auditRemark) {
        QueryWrapper<Partner> queryWrapper = new QueryWrapper<Partner>().eq("delete_flag", false)
                .notIn("partner_type", 0, 3).notIn("audit_state", PartnerStatusEnum.REFUSED).eq("member_id", id);
        List<Partner> partnerList = partnerMapper.selectList(queryWrapper);
        if (partnerList.size() != 1) {
            throw new ServiceException(ResultCode.USER_PARTNER_ERROR);
        }
        Partner partner = partnerList.get(0);

        if (!"APPLYING".equals(partner.getAuditState())) {
            throw new ServiceException(ResultCode.USER_PARTNER_AUDIT_ERROR);
        }
        if ("PASS".equals(auditState) && ((1 == partner.getPartnerType() || 4 == partner.getPartnerType())
                || (2 == partner.getPartnerType() && partner.getPayState() == 1))) {
            partner.setBeginTime(new Date());
            partner.setEndTime(getOneYearLaterDate());
        }
        partner.setAuditState(auditState);
        partner.setAuditRemark(auditRemark);
        partner.setAuditTime(new Date());
        if ("REFUSED".equals(auditState)) {
            partner.setDeleteFlag(true);
            partner.setPartnerState(1);
            return partnerService.updateById(partner);
        }
        // 添加推广码
        Member member = memberMapper.selectById(id);
        if (StringUtils.isEmpty(member.getPromotionCode())) {
            member.setPromotionCode(eextensionService.getExtension());
        }
        if ("PASS".equals(auditState) && 4 == partner.getPartnerType()) {
            // 城市
            member.setExtensionFlag(Boolean.FALSE);
        }

        // 在滚动消息里添加数据
        RollMessage rollMessage = new RollMessage();
        if (partner.getPartnerType() == 1) {
            rollMessage.setContent(member.getNickName() + "成为事业合伙人");
        } else if (partner.getPartnerType() == 2) {
            rollMessage.setContent(member.getNickName() + "成为天使合伙人");
        } else if (partner.getPartnerType() == 3) {
            rollMessage.setContent(member.getNickName() + "成为城市代理商");
        } else {
            rollMessage.setContent(member.getNickName() + "成为合伙人");
        }
        rollMessage.setCreateBy(member.getId());
        rollMessage.setCreateTime(new Date());
        rollMessage.setType(2);
        rollMessage.setStatus(1);
        rollMessage.setDelFlag(false);
        rollMessage.setId(String.valueOf(SnowFlake.getId()));
        boolean save = rollMessageMapper.insert(rollMessage) > 0;

        if (partner.getPartnerType() == 4) {
            QueryWrapper<Role> wrapper = Wrappers.query();
            wrapper.eq("name", UserEnums.AGENT.getRole());
            wrapper.eq("parent_id", 0);
            Role role = roleService.getOne(wrapper);

            // 地区Id
            String regionId = partner.getRegionId();
            Role roleNew = new Role();
            if (StringUtils.isEmpty(regionId)) {
                throw new ServiceException(ResultCode.USER_PARTNER_ERROR);
            } else {
                // 创建角色
                String itemAdCodOrName = regionService.getItemAdCodOrName(regionId) + "城市合伙人"; // 角色名称
                roleNew.setName(UserEnums.AGENT.getRole());
                roleNew.setRoleName(itemAdCodOrName);
                roleNew.setCreateBy(UserContext.getCurrentUser().getUsername());
                roleNew.setCreateTime(new Date());
                roleNew.setParentId(role.getId());
                roleNew.setAncestors(role.getAncestors() + "," + role.getId());
                roleNew.setSortOrder(0);
                roleNew.setState("0"); // 0平台角色 1商家角色
                roleService.save(roleNew);
            }

            AdminUser adminUser = new AdminUser();
            adminUser.setMobile(member.getMobile());
            adminUser.setAvatar(member.getFace());
            adminUser.setUsername(member.getUsername());
            adminUser.setNickName(member.getNickName());
            adminUser.setIsSuper(false);
            adminUser.setPassword(member.getPassword());
            adminUser.setStatus(true);
            adminUser.setPromotionCode(member.getPromotionCode());
            adminUser.setMemberId(member.getId());
            QueryWrapper<Partner> queryWrapper2 = new QueryWrapper<Partner>().eq("delete_flag", false)
                    .eq("partner_type", 4).eq("member_id", id);
            List<Partner> partnerList1 = partnerMapper.selectList(queryWrapper2);
            if (partnerList.size() != 1) {
                throw new ServiceException(ResultCode.USER_PARTNER_ERROR);
            }
            Partner partner1 = partnerList1.get(0);
            adminUser.setRegion(partner1.getRegion());
            adminUser.setRegionId(partner1.getRegionId());
            adminUser.setRoleIds(roleNew.getId());
            adminUserService.save(adminUser);
            // 查询回来她上级所有的权限
            List<RoleMenu> byRoleId = roleMenuService.findByRoleId(role.getId());
            // 删除并更新当前新增用户的权限
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("role_id", roleNew.getId());
            roleMenuService.remove(queryWrapper3);
            // 新增当前用户的数据权限
            for (RoleMenu item : byRoleId) {
                item.setId(null);
                item.setRoleId(roleNew.getId());
                item.setCreateBy(UserContext.getCurrentUser().getUsername());
                item.setCreateTime(new Date());
                roleMenuService.save(item);
            }
            // 删除角色和用户管理表
            userRoleService.remove(queryWrapper3);
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleNew.getId());
            userRole.setUserId(adminUser.getId());
            userRoleService.save(userRole);
            // List<String> list = new ArrayList<>();
            // list.add(roleNew.getId());
            // adminUserService.updateRole(adminUser.getId(), list);
        }

        // 保留变更记录
        RegionDetail regionDetail = new RegionDetail();
        regionDetail.setMemberId(id);
        regionDetail.setBeforeAdCode(member.getLocation());
        regionDetail.setBeforeName(regionService.getItemAdCodOrName(member.getLocation()));
        regionDetail.setAfterAdCode(partner.getRegionId());
        regionDetail.setAfterName(regionService.getItemAdCodOrName(partner.getRegionId()));
        regionDetailMapper.insert(regionDetail);

        // 申请区域修改个人区域
        member.setLocation(partner.getRegionId());
        memberMapper.updateById(member);
        return partnerService.updateById(partner);
    }

    @Override
    public Boolean updatePartner(String id, String partnerRegion) {
        QueryWrapper<Partner> queryWrapper = new QueryWrapper<Partner>().eq("delete_flag", false)
                .notIn("partner_type", 0, 3)
                .and(wa -> wa.notIn("audit_state", PartnerStatusEnum.REFUSED, PartnerStatusEnum.WAIT_SUBMIT).or()
                        .isNull("audit_state"))
                .eq("member_id", id);
        List<Partner> partnerList = partnerMapper.selectList(queryWrapper);
        if (partnerList.size() > 1) {
            throw new ServiceException(ResultCode.USER_PARTNER_ERROR);
        }
        Partner partner = partnerList.get(0);
        if (StringUtils.isNotEmpty(partnerRegion)) {
            List<String> itemAdCod = regionService.getPartnerAdCode(partnerRegion, partner.getPartnerType().toString());
            if (itemAdCod != null && itemAdCod.get(0) != null)
                partner.setRegionId(itemAdCod.get(0));
        }
        String[] split2 = partnerRegion.split(",");
        String adCodeName = "";
        for (int a = 0; a < split2.length && a <= 3; a++) {
            Region byId = regionService.getById(split2[a]);
            if (byId != null)
                adCodeName += byId.getName();
        }
        partner.setRegion(adCodeName);
        return partnerService.updateById(partner);
    }

    private Role getRoleByType(Integer partnerType) {

        if (partnerType == null) {
            throw new ServiceException(ResultCode.USER_PARTNER_TYPE_ERROR);
        }

        QueryWrapper<Role> roleQw = new QueryWrapper<Role>().eq("delete_flag", false);

        switch (partnerType) {
            case 1:
                roleQw.eq("name", "事业合伙人");
                break;
            case 2:
                roleQw.eq("name", "天使合伙人");
                break;
            case 3:
                roleQw.eq("name", "推广员");
                break;
            case 4:
                roleQw.eq("name", "代理商");
                break;
            default:
                throw new ServiceException(ResultCode.USER_PARTNER_TYPE_ERROR);
        }
        List<Role> roleList = roleMapper.selectList(roleQw);
        if (roleList.isEmpty()) {
            throw new ServiceException(ResultCode.USER_PARTNER_TYPE_ERROR);
        }

        return roleList.get(0);
    }

    private RateSetting getRateSettingByRoleId(String roleId) {
        if (roleId == null) {
            throw new ServiceException(ResultCode.USER_PARTNER_TYPE_ERROR);
        }

        QueryWrapper<RateSetting> rateSettingQw = new QueryWrapper<RateSetting>().eq("delete_flag", false).eq("role_id",
                roleId);
        List<RateSetting> rateSettingList = rateSettingMapper.selectList(rateSettingQw);
        if (rateSettingList.isEmpty()) {
            throw new ServiceException(ResultCode.USER_PARTNER_TYPE_ERROR);
        }
        return rateSettingList.get(0);
    }

    private Date getOneYearLaterDate() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, 3);
        return c.getTime();
    }

    @Override
    public Member authentication(String realName, String idCardNumber) {
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        Member member = this.getById(tokenUser.getId());
        this.baseMapper.authentication(realName, idCardNumber, member.getId());
        // 会员的姓名和身份证号
        // LambdaUpdateWrapper<Member> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        // lambdaUpdateWrapper.eq(Member::getId, member.getId());
        // lambdaUpdateWrapper.set(Member::getRealName, realName);
        // lambdaUpdateWrapper.set(Member::getIdCardNumber, idCardNumber);
        // this.update(lambdaUpdateWrapper);
        Member real_member = this.getById(tokenUser.getId());
        return real_member;
    }

    @Override
    public Member authVerify(AuthVerifyDto authVerifyDto) {
        log.info("实名认证，入参:{}", JSON.toJSONString(authVerifyDto));
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        Member member = this.getById(tokenUser.getId());
        if (member == null) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        member.setIdCardNumber(authVerifyDto.getIdCardNumber());
        member.setHomeTown(authVerifyDto.getHomeTown());
        member.setSex(authVerifyDto.getSex());
        member.setBirthday(authVerifyDto.getBirthday());
        member.setRealName(authVerifyDto.getRealName());
        this.baseMapper.updateById(member);
        return member;
    }

    /************
     * 查询登录用户权限******修改计算实际到账金额和手续费************20220623
     *****************************/
    @Override
    public String findByPartner(String id) {
        return partnerMapper.findByPartner(id);
    }

    @Override
    public MemberDetailsVo getMemberDetails(MemberDetailsVo memberDetailsVo) {
        Member member = this.baseMapper.selectById(memberDetailsVo.getId());
        if (member != null) {
            memberDetailsVo.setUsername(member.getUsername()); // 用户名
            memberDetailsVo.setNickName(member.getNickName()); // 昵称
            memberDetailsVo.setLastLoginDate(member.getLastLoginDate()); // 上次登录时间
            memberDetailsVo.setPromotionCode(member.getPromotionCode());
        }
        GradeVO byId = gradeService.getById(member.getGradeId());
        if (byId != null) {
            memberDetailsVo.setGradeIdName(byId.getName());// 等级
        } else {
            memberDetailsVo.setGradeIdName("游客");// 等级
        }
        memberDetailsVo.setLocationName(regionService.getItemAdCodOrName(member.getLocation())); // 区域
        memberDetailsVo.setMobile(member.getMobile());// 手机号
        MemberVO byMemberId = eextensionService.findByMemberId(memberDetailsVo.getId());
        if (byMemberId != null) {
            memberDetailsVo.setExtensionMobile(byMemberId.getMobile()); // 推广人手机号
            memberDetailsVo.setExtensionName(byMemberId.getRealName()); // 推广人姓名
        }
        memberDetailsVo.setCreateTime(member.getCreateTime());// 注册时间
        MemberDetailsVo memberDetailsVo1 = this.baseMapper.getMemberDetailsVo(memberDetailsVo.getId());
        if (memberDetailsVo1 != null) {
            memberDetailsVo.setMemberEndTime(memberDetailsVo1.getMemberEndTime());// 到期时间
        }
        memberDetailsVo.setFace(member.getFace());// 头像
        /**
         * 合伙人-B商家需要的字段
         */
        Store store = storeService.getById(member.getStoreId()); // 店铺
        if (store != null) {
            memberDetailsVo.setStoreName(store.getStoreName());
            memberDetailsVo.setStoreId(member.getStoreId());
        }
        // 根据会员Id查询所有的钱包
        List<MemberWallet> memberWalletById = memberWalletService.getMemberWalletById(member.getId());
        if (memberWalletById.size() > 0) {
            memberWalletById.forEach(intm -> {
                switch (intm.getOwner()) {
                    case "SALE": // 销售钱包余额
                        memberDetailsVo.setSaleMoney(intm.getMemberWallet() == null
                                ? 0.00
                                : CurrencyUtil.roundDown(intm.getMemberWallet(), 2)); // 销售钱包余额
                        break;
                    case "PROMOTE": // 推广钱包余额
                        memberDetailsVo.setPromoteMoney(intm.getMemberWallet() == null
                                ? 0.00
                                : CurrencyUtil.roundDown(intm.getMemberWallet(), 2)); // 推广钱包余额
                        break;
                    case "RECHARGE":// 充值钱包余额
                        memberDetailsVo.setRechargeMoney(intm.getMemberWallet() == null
                                ? 0.00
                                : CurrencyUtil.roundDown(intm.getMemberWallet(), 2)); // 充值钱包余额
                        break;
                    case "PROMOTE_FW":// 推广会员费钱包余额
                        memberDetailsVo.setPromoteFwMoney(intm.getMemberWallet() == null
                                ? 0.00
                                : CurrencyUtil.roundDown(intm.getMemberWallet(), 2)); // 推广会员费钱包余额
                        break;
                    case "PROMOTE_HY":// 推广服务费钱包余额
                        memberDetailsVo.setPromoteHyMoney(intm.getMemberWallet() == null
                                ? 0.00
                                : CurrencyUtil.roundDown(intm.getMemberWallet(), 2)); // 推广服务费钱包余额
                        break;
                }
            });
        }
        // 根据不同状态获取不同合伙人的端口费 @ApiModelProperty(value = "状态
        // 天使合伙人：ANGEL_PARTNER；事业合伙人：BUSINESS_PARTNER；城市合伙人（也叫：代理商）：AGENT")

        if (StringUtils.isNotEmpty(memberDetailsVo.getState())) { // 当传过来的状态不为空的时候进行搜索端口费用
            String name = "";
            switch (memberDetailsVo.getState()) {
                case "ANGEL_PARTNER": // 天使合伙人
                    name = UserEnums.ANGEL_PARTNER.getRole();
                    break;
                case "BUSINESS_PARTNER": // 事业合伙人
                    name = UserEnums.BUSINESS_PARTNER.getRole();
                    break;
                case "AGENT":// 城市合伙人（也叫：代理商）
                    name = UserEnums.AGENT.getRole();
                    break;
            }
            Role role = roleService.seleGetById(name);
            // 根据Role角色Id和memberId查询到期时间
            Partner partner = partnerService.seleGerByRoleMember(memberDetailsVo.getId(), role.getId());
            if (partner != null) {
                memberDetailsVo.setBeginTime(partner.getBeginTime()); // 开始时间
                memberDetailsVo.setEndTime(partner.getEndTime()); // 到期时间
            }
            // 查询最新的充值记录
            RechargeVO rechargeMember = rechargeMapper.getRechargeMember(memberDetailsVo.getId());
            if (rechargeMember != null) {
                memberDetailsVo.setPrice(rechargeMember.getPrice());
                memberDetailsVo.setYiBei(rechargeMember.getYiBei());
                memberDetailsVo.setPayTime(rechargeMember.getPayTime());
            }
        }
        return memberDetailsVo;
    }

    /**
     * 收入详情列表
     *
     * @param memberIncomeVo
     * @param page
     * @return
     */
    @Override
    public IPage<MemberIncomeVo> getIncomeByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            if (memberIncomeVo.getStart().equals("CHARGE")) { // 查询充值的
                list.add(4); // 普通充值
            } else if (memberIncomeVo.getStart().equals("TURN")) { // 转账
                list.add(99); // 转账
            } else if (memberIncomeVo.getStart().equals("MEETING")) { // 会员
                list.add(43); // 充值银卡
                list.add(44); // 充值金卡
            }
        } else {
            list.add(4); // 普通充值
            list.add(43); // 充值银卡
            list.add(44); // 充值金卡
            list.add(99); // 转账
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(e.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(e.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in("e.incomeType", list);
        queryWrapper.orderByDesc("e.incomeTime");
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("e.memberId", memberIncomeVo.getMemberId());
        }
        IPage<MemberIncomeVo> memberVOIPage = baseMapper.getIncomeByPage(PageUtil.initPage(page), queryWrapper);
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return memberVOIPage;
    }

    @Override
    public Map getIncomeByPageCount(MemberIncomeVo memberIncomeVo) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            if (memberIncomeVo.getStart().equals("CHARGE")) { // 查询充值的
                list.add(4); // 普通充值
            } else if (memberIncomeVo.getStart().equals("TURN")) { // 转账
                list.add(99); // 转账
            } else if (memberIncomeVo.getStart().equals("MEETING")) { // 会员
                list.add(43); // 充值银卡
                list.add(44); // 充值金卡
            }
        } else {
            list.add(4); // 普通充值
            list.add(43); // 充值银卡
            list.add(44); // 充值金卡
            list.add(99); // 转账
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {

            queryWrapper.le("DATE_FORMAT(e.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(e.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in("e.incomeType", list);
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("e.memberId", memberIncomeVo.getMemberId());
        }
        Map<String, Object> incomeByPageCount = baseMapper.getIncomeByPageCount(queryWrapper);
        return incomeByPageCount;
    }

    @Override
    public IPage<MemberExpenditureVo> getBranchByPage(MemberExpenditureVo memberExpenditureVo, PageVO page) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "MEETING":
                    list.add(3); // 支出会员费
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                    break;
            }
        } else {
            list.add(3); // 支出会员费
            list.add("OFFLINE"); // 线下订单
            list.add("NORMAL"); // 线上订单
            list.add("VIRTUAL"); // 虚拟订单
        }
        queryWrapper.in("e.expenditureType", list);
        // 除了未付款和已取消全查出来
        List listNot = new ArrayList();
        listNot.add("UNPAID");// 未付款
        listNot.add("CANCELLED");// 已取消
        queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(e.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(e.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("e.memberId", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("e.expenditureTime");
        IPage<MemberExpenditureVo> branchByPage = baseMapper.getBranchByPage(PageUtil.initPage(page), queryWrapper);
        branchByPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return branchByPage;
    }

    @Override
    public Map getBranchByPageCount(MemberExpenditureVo memberExpenditureVo) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "MEETING":
                    list.add(3); // 支出会员费
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                    break;
            }
        } else {
            list.add(3); // 支出会员费
            list.add("OFFLINE"); // 线下订单
            list.add("NORMAL"); // 线上订单
            list.add("VIRTUAL"); // 虚拟订单
        }
        queryWrapper.in("e.expenditureType", list);
        // 除了未付款和已取消全查出来
        List listNot = new ArrayList();
        listNot.add("UNPAID");// 未付款
        listNot.add("CANCELLED");// 已取消
        queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(e.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(e.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("e.memberId", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("e.expenditureTime");
        Map<String, Object> branchByPageCount = baseMapper.getBranchByPageCount(queryWrapper);
        return branchByPageCount;
    }

    @Override
    public IPage<MemberAbnormalVo> getDisableMemberPage(MemberAbnormalVo memberAbnormalVo, PageVO page) {
        QueryWrapper<MemberAbnormalVo> queryWrapper = Wrappers.query();
        // 获取区域下的所有地区
        if (StringUtils.isNotEmpty(memberAbnormalVo.getRegionId())) {
            List itemAdCod = regionService.getItemAdCod(memberAbnormalVo.getRegionId());
            queryWrapper.in("a.location", itemAdCod);
        }
        // 用户名查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberAbnormalVo.getUsername()), "a.username",
                memberAbnormalVo.getUsername());
        // 用户昵称
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberAbnormalVo.getNickName()), "a.nickName",
                memberAbnormalVo.getNickName());
        // 用户手机号
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberAbnormalVo.getMobile()), "a.mobile",
                memberAbnormalVo.getMobile());
        // 金卡银卡
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberAbnormalVo.getLevel()), "a.level",
                memberAbnormalVo.getLevel());
        // 时间查询
        if (StringUtils.isNotEmpty(memberAbnormalVo.getStartDate())
                && StringUtils.isNotEmpty(memberAbnormalVo.getEndDate())) {
            queryWrapper.le("a.disableTime", memberAbnormalVo.getEndDate());
            queryWrapper.ge("a.disableTime", memberAbnormalVo.getStartDate());
        }
        queryWrapper.eq("a.delete_flag", 0);
        queryWrapper.eq(" a.disabled", 0); // 只查询禁用的
        queryWrapper.orderByDesc("a.createTime");
        IPage<MemberAbnormalVo> disableMemberPage = this.baseMapper.getDisableMemberPage(PageUtil.initPage(page),
                queryWrapper);
        // 根据ad_code查询区域
        disableMemberPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
            MemberVO byMemberId = eextensionService.findByMemberId(item.getId());
            if (byMemberId != null) {
                item.setMobileExte(byMemberId.getMobile());// 获取推广人手机号
            }
        });
        return disableMemberPage;
    }

    @Override
    public Member setPaymentPwd(PaymentPwdDto paymentPwdDto) {
        log.info("设置密码，入参:{}", JSON.toJSONString(paymentPwdDto));
        Member member = this.getById(paymentPwdDto.getMemberId());
        if (paymentPwdDto.getNewPassword().equals(paymentPwdDto.getConfirmPassword())) {
            member.setPaymentPassword(new BCryptPasswordEncoder().encode(paymentPwdDto.getNewPassword()));
            this.updateById(member);
            return member;
        }
        return member;
    }

    @Override
    public Member initPaymentPwd(PaymentPwdDto paymentPwdDto) {
        log.info("初始支付化密码，入参:{}", JSON.toJSONString(paymentPwdDto));
        Member member = this.baseMapper.selectById(paymentPwdDto.getMemberId());
        member.setNoSecret(paymentPwdDto.getNoSecret());
        if (StringUtils.isNotEmpty(paymentPwdDto.getNewPassword())
                && paymentPwdDto.getNewPassword().equals(paymentPwdDto.getConfirmPassword())) {
            member.setPaymentPassword(new BCryptPasswordEncoder().encode(paymentPwdDto.getNewPassword()));
        }
        this.updateById(member);
        return member;
    }

    @Override
    public PaymentPwdVo getPaymentPwd(String memberId) {
        Member member = this.baseMapper.selectById(memberId);
        if (member == null) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        PaymentPwdVo pwdVo = new PaymentPwdVo();
        pwdVo.setNoSecret(member.getNoSecret());
        if (StringUtils.isNotEmpty(member.getPaymentPassword())) {
            pwdVo.setSetPwd(Boolean.TRUE);
        } else {
            pwdVo.setSetPwd(Boolean.FALSE);
        }
        return pwdVo;
    }

    /**
     * 撤销合伙人 根据memberId 获取li_partner 表的合伙人数据 更新 partner_state 、delete_flag 字段
     * 根据memberId 获取 li_member 表会员数据 根据推广码 promotion_code字段 获取li_extension 数据
     * 更新delete_flag 字段
     *
     * @param memberId
     * @return
     */

    @Override
    public RevokePartnerVo revokePartnerPage(String memberId) {
        return this.baseMapper.getDetail(memberId);
    }

    @Override
    public Boolean revokePartnerVerify(String memberId) {
        AuditPartner partner = auditPartnerMapper.getAllByMemberIdAndAuditStatusEquals(memberId,
                AuditPartnerStatus.AUDITING.getCode());
        if (partner != null) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean applyRevokePartner(String revokeMsg, String memberId) {
        AuditPartner partner = auditPartnerMapper.getAllByMemberIdAndAuditStatusEquals(memberId,
                AuditPartnerStatus.AUDITING.getCode());
        if (partner != null) {
            throw new ServiceException(ResultCode.USER_PARTNER_AUDIT_ERROR);
        }
        AuditPartner auditPartner = new AuditPartner();
        auditPartner.setAuditStatus(AuditPartnerStatus.AUDITING.getCode());
        auditPartner.setMemberId(memberId);
        auditPartner.setRevokeMsg(revokeMsg);
        int num = auditPartnerMapper.insert(auditPartner);
        if (num != 1) {
            throw new ServiceException(ResultCode.ERROR);
        }
        return Boolean.TRUE;
    }

    @Override
    public RevokeApplyVo applyRevokePage(String memberId) {
        AuditPartner auditPartner = auditPartnerMapper.verifyAllByMemberId(memberId);
        if (auditPartner != null) {
            RevokeApplyVo revokeApplyVo = new RevokeApplyVo();
            revokeApplyVo.setRevokeMsg(auditPartner.getRevokeMsg());
            revokeApplyVo.setAuditStatus(auditPartner.getAuditStatus());
            revokeApplyVo.setCreateTime(DateUtil.toString(auditPartner.getCreateTime()));
            revokeApplyVo.setMemberId(auditPartner.getMemberId());
            revokeApplyVo.setAuditDate(DateUtil.toString(auditPartner.getAuditDate()));
            revokeApplyVo.setAuditMsg(auditPartner.getAuditMsg());
            revokeApplyVo.setId(auditPartner.getId());
            return revokeApplyVo;
        }
        return new RevokeApplyVo();
    }

    @Override
    public Boolean applyRevoke(String auditId) {
        AuditPartner auditPartner = auditPartnerMapper.selectById(auditId);
        if (auditPartner != null) {
            auditPartner.setAuditStatus(AuditPartnerStatus.REVOKE.getCode());
            int num = auditPartnerMapper.updateById(auditPartner);
            if (num != 1) {
                throw new ServiceException(ResultCode.ERROR);
            }
            return Boolean.TRUE;
        }
        throw new ServiceException(ResultCode.ERROR);
    }

    @Override
    public List<MemberVO> getUserInfoById(List<String> memberIds, List<String> storeIds) {
        QueryWrapper<MemberVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(CollectionUtils.isNotEmpty(memberIds), "m.id", memberIds);
        queryWrapper.in(CollectionUtils.isNotEmpty(storeIds), "s.id", storeIds);
        return this.baseMapper.getUserInfoById(queryWrapper);
    }

    @Override
    public IPage<MemberVO> getDisableMemberPageAll(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<MerchantsMemberVo> queryWrapper = Wrappers.query();
        QueryWrapper<Partner> wrapper = new QueryWrapper<>();
        Member member = this.baseMapper.selectById(memberSearchVO.getId());
        wrapper.eq("delete_flag", 0);
        wrapper.eq("audit_state", "PASS");
        wrapper.eq("member_id", memberSearchVO.getId());
        wrapper.last("limit 1");
        Partner partner = partnerService.getOne(wrapper);
        if (partner != null && StringUtils.equals(partner.getPartnerType().toString(), "1")) {
            queryWrapper.eq("b.have_store", "1");
        }
        if (member != null && StringUtils.isNotEmpty(member.getPromotionCode())) {
            queryWrapper.eq("a.extension", member.getPromotionCode()); // 推广码
            queryWrapper.eq(StringUtils.isNotEmpty(memberSearchVO.getMobile()), "b.mobile", memberSearchVO.getMobile()); // 电话号码
            queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getStoreName()), "s.store_name", memberSearchVO.getStoreName()); // 电话号码
            if (memberSearchVO.getBeginTime() != null && memberSearchVO.getEndTime() != null) {
                // queryWrapper.between("a.create_time", memberSearchVO.getBeginTime(),
                // memberSearchVO.getEndTime());
                queryWrapper.le("DATE_FORMAT(a.create_time,'%Y-%m-%d')",
                        DateUtil.toString(memberSearchVO.getEndTime(), "yyyy-MM-dd"));
                queryWrapper.ge("DATE_FORMAT(a.create_time,'%Y-%m-%d')",
                        DateUtil.toString(memberSearchVO.getBeginTime(), "yyyy-MM-dd"));
            }
            // 区域
            if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
                List list = regionService.getItemAdCod(memberSearchVO.getRegionId());
                queryWrapper.in(CollectionUtils.isNotEmpty(list), "ls.ad_code", list);
            }
            queryWrapper.groupBy("a.member_id");
            queryWrapper.eq("a.delete_flag", "0");
            queryWrapper.orderByDesc("b.create_time");
            IPage<MemberVO> disableMemberPageAll = this.baseMapper.getDisableMemberPageAll(PageUtil.initPage(page),
                    queryWrapper, member.getId());
            disableMemberPageAll.getRecords().forEach(item -> {
                if (StringUtils.isNotEmpty(item.getLocation()))
                    item.setLocationName(regionService.getItemAdCodOrName(item.getLocation())); // 地区
            });
            return disableMemberPageAll;
        }
        return null;
    }

    @Override
    public IPage<MemberVO> getDisableMemberPageAll2(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<Partner> wrapper = new QueryWrapper<>();
        wrapper.eq("partner_type", "4");// 代理商
        wrapper.eq("delete_flag", 0);
        wrapper.eq("audit_state", "PASS");
        wrapper.eq("member_id", memberSearchVO.getId());
        wrapper.last("limit 1");
        Partner partner = partnerService.getOne(wrapper);

        QueryWrapper<MerchantsMemberVo> queryWrapper = Wrappers.query();
        if (partner != null && StringUtils.isNotEmpty(partner.getRegionId())) {
            List list = regionService.getPartnerAdCode(partner.getRegionId(), "4");
            queryWrapper.in(list != null && list.size() > 0, "b.location", list);

            queryWrapper.eq(StringUtils.isNotEmpty(memberSearchVO.getMobile()), "b.mobile", memberSearchVO.getMobile()); // 电话号码
            if (memberSearchVO.getBeginTime() != null && memberSearchVO.getEndTime() != null) {
                // queryWrapper.between("b.create_time", memberSearchVO.getBeginTime(),
                // memberSearchVO.getEndTime());
                queryWrapper.le("DATE_FORMAT(b.create_time,'%Y-%m-%d')",
                        DateUtil.toString(memberSearchVO.getEndTime(), "yyyy-MM-dd"));
                queryWrapper.ge("DATE_FORMAT(b.create_time,'%Y-%m-%d')",
                        DateUtil.toString(memberSearchVO.getBeginTime(), "yyyy-MM-dd"));
            }
            queryWrapper.groupBy("b.id");
            queryWrapper.eq("b.delete_flag", "0");
            queryWrapper.eq("b.have_store", "0");
            // queryWrapper.isNull("p.id");
            queryWrapper.and(wa -> wa.isNull("p.audit_state").or().ne("p.audit_state", "PASS"));
            queryWrapper.orderByDesc("b.create_time");
            IPage<MemberVO> disableMemberPageAll = this.baseMapper.getDisableMemberPageAll2(PageUtil.initPage(page),
                    queryWrapper, memberSearchVO.getId());
            disableMemberPageAll.getRecords().forEach(item -> {
                if (StringUtils.isNotEmpty(item.getLocation()))
                    item.setLocationName(regionService.getItemAdCodOrName(item.getLocation())); // 地区
            });
            return disableMemberPageAll;
        }
        return new Page<>();
    }

    /**
     * 销售钱包收入明细
     *
     * @param memberIncomeVo
     * @param page
     * @return
     */
    @Override
    public IPage<MemberIncomeVo> getIncomeSaleByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            switch (memberIncomeVo.getStart()) {
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                    break;
            }
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in(list.size() > 0, "a.incomeType", list);
        queryWrapper.orderByDesc("a.incomeTime");
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payee", memberIncomeVo.getMemberId());
        }
        IPage<MemberIncomeVo> memberVOIPage = baseMapper.getIncomeSaleByPage(PageUtil.initPage(page), queryWrapper);
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return memberVOIPage;
    }

    /**
     * 销售钱包收入汇总
     *
     * @param memberIncomeVo
     * @return
     */
    @Override
    public Map<String, Object> getIncomeSaleByPageCount(MemberIncomeVo memberIncomeVo) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            switch (memberIncomeVo.getStart()) {
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                    break;
            }
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in(list.size() > 0, "a.incomeType", list);
        queryWrapper.orderByDesc("a.incomeTime");
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payee", memberIncomeVo.getMemberId());
        }
        Map memberVOIPage = baseMapper.getIncomeSaleByPageCount(queryWrapper);
        return memberVOIPage;
    }

    /**
     * 销售钱包支出明细
     *
     * @param memberExpenditureVo
     * @param page
     * @return
     */
    @Override
    public IPage<MemberExpenditureVo> getBranchSaleByPage(MemberExpenditureVo memberExpenditureVo, PageVO page) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "TRANSFER":
                    list.add("TRANSFER"); // 转账
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                case "WITHDRAWAL":
                    list.add("WITHDRAWAL"); // 提现
                    break;
            }
        }
        queryWrapper.in(list != null && list.size() > 0, "a.expenditureType", list);
        // //除了未付款和已取消全查出来
        // List listNot = new ArrayList();
        // listNot.add("UNPAID");//未付款
        // listNot.add("CANCELLED");//已取消
        // queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payer", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("a.expenditureTime");
        queryWrapper.groupBy("a.receivableNo");
        IPage<MemberExpenditureVo> branchByPage = baseMapper.getBranchSaleByPage(PageUtil.initPage(page), queryWrapper);
        branchByPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return branchByPage;
    }

    /**
     * 销售钱包支出汇总
     *
     * @param
     * @return
     */
    @Override
    public Map<String, Object> getBranchSaleByPageCount(MemberExpenditureVo memberExpenditureVo) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "TRANSFER":
                    list.add("TRANSFER"); // 转账
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                case "WITHDRAWAL":
                    list.add("WITHDRAWAL"); // 提现
                    break;
            }
        }
        queryWrapper.in(list != null && list.size() > 0, "a.expenditureType", list);
        // //除了未付款和已取消全查出来
        // List listNot = new ArrayList();
        // listNot.add("UNPAID");//未付款
        // listNot.add("CANCELLED");//已取消
        // queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payer", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("a.expenditureTime");
        queryWrapper.groupBy("a.receivableNo");
        Map branchByPage = baseMapper.getBranchSaleByPageCount(queryWrapper);
        return branchByPage;
    }

    /**
     * 推广钱包收入明细
     *
     * @param memberIncomeVo
     * @param page
     * @return
     */
    @Override
    public IPage<MemberIncomeVo> getIncomePromoteByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            if (memberIncomeVo.getStart().equals("MEMBERCOMMISSION")) { // 会员费用
                list.add("WALLET_COMMISSION_HY"); // 佣金提成-会员费
            } else if (memberIncomeVo.getStart().equals("CONSUMPTIONCOMMISSION")) { // 消费分佣
                list.add("WALLET_COMMISSION_FW"); // 佣金提成-服务费
                list.add("WALLET_COMMISSION_TS"); // 佣金提成-天使
                list.add("WALLET_COMMISSION_SY"); // 佣金提成-事业
            } else if (memberIncomeVo.getStart().equals("REFUND")) { // 退费
                list.add("WALLET_COMMISSION_HY_REFUND"); // 佣金提成退款-会员费
                list.add("WALLET_COMMISSION_FW_REFUND"); // 佣金提成退款-服务费
                list.add("WALLET_COMMISSION_TS_REFUND"); // 佣金提成退款-天使
                list.add("WALLET_COMMISSION_SY_REFUND"); // 佣金提成退款-事业
                list.add("WALLET_REFUND"); // 余额退款
                list.add("WALLET_COLLECT_REFUND"); // 运费退款
            }
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in(list.size() > 0, "a.incomeType", list);
        queryWrapper.orderByDesc("a.incomeTime");
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payee", memberIncomeVo.getMemberId());
        }
        queryWrapper.eq(StringUtils.isNotEmpty(memberIncomeVo.getOwner()), "a.owner", memberIncomeVo.getOwner());
        queryWrapper.groupBy("a.receivableNo");
        IPage<MemberIncomeVo> memberVOIPage = baseMapper.getIncomePromoteByPage(PageUtil.initPage(page), queryWrapper);
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return memberVOIPage;

    }

    /**
     * 推广钱包收入汇总
     *
     * @param memberIncomeVo
     * @return
     */
    @Override
    public Map<String, Object> getIncomePromoteByPageCount(MemberIncomeVo memberIncomeVo) {
        QueryWrapper<MemberIncomeVo> queryWrapper = Wrappers.query();
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberIncomeVo.getStart())) {
            if (memberIncomeVo.getStart().equals("MEMBERCOMMISSION")) { // 会员费用
                list.add("WALLET_COMMISSION_HY"); // 佣金提成-会员费
            } else if (memberIncomeVo.getStart().equals("CONSUMPTIONCOMMISSION")) { // 消费分佣
                list.add("WALLET_COMMISSION_FW"); // 佣金提成-服务费
                list.add("WALLET_COMMISSION_TS"); // 佣金提成-天使
                list.add("WALLET_COMMISSION_SY"); // 佣金提成-事业
            } else if (memberIncomeVo.getStart().equals("REFUND")) { // 退费
                list.add("WALLET_COMMISSION_HY_REFUND"); // 佣金提成退款-会员费
                list.add("WALLET_COMMISSION_FW_REFUND"); // 佣金提成退款-服务费
                list.add("WALLET_COMMISSION_TS_REFUND"); // 佣金提成退款-天使
                list.add("WALLET_COMMISSION_SY_REFUND"); // 佣金提成退款-事业
                list.add("WALLET_REFUND"); // 余额退款
                list.add("WALLET_COLLECT_REFUND"); // 运费退款
            }
        }
        // 时间查询
        if (StringUtils.isNotEmpty(memberIncomeVo.getStartDate())
                && StringUtils.isNotEmpty(memberIncomeVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getEndDate());
            queryWrapper.ge("DATE_FORMAT(a.incomeTime,'%Y-%m-%d')", memberIncomeVo.getStartDate());
        }
        queryWrapper.in(list.size() > 0, "a.incomeType", list);
        queryWrapper.orderByDesc("a.incomeTime");
        if (StringUtils.isNotEmpty(memberIncomeVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payee", memberIncomeVo.getMemberId());
        }
        queryWrapper.eq(StringUtils.isNotEmpty(memberIncomeVo.getOwner()), "a.owner", memberIncomeVo.getOwner());
        queryWrapper.groupBy("a.receivableNo");
        Map memberVOIPage = baseMapper.getIncomePromoteByPageCount(queryWrapper);

        return memberVOIPage;
    }

    /**
     * 推广钱包支出明细
     *
     * @param memberExpenditureVo
     * @param page
     * @return
     */
    @Override
    public IPage<MemberExpenditureVo> getBranchPromoteByPage(MemberExpenditureVo memberExpenditureVo, PageVO page) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "TRANSFER":
                    list.add("TRANSFER"); // 转账
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                case "WITHDRAWAL":
                    list.add("WITHDRAWAL"); // 提现
                    break;
            }
        }
        queryWrapper.in(list != null && list.size() > 0, "a.expenditureType", list);
        // //除了未付款和已取消全查出来
        // List listNot = new ArrayList();
        // listNot.add("UNPAID");//未付款
        // listNot.add("CANCELLED");//已取消
        // queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payer", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("a.expenditureTime");

        queryWrapper.eq(StringUtils.isNotEmpty(memberExpenditureVo.getOwner()), "a.owner",
                memberExpenditureVo.getOwner());
        queryWrapper.groupBy("a.receivableNo");
        IPage<MemberExpenditureVo> branchByPage = baseMapper.getBranchPromoteByPage(PageUtil.initPage(page),
                queryWrapper);
        branchByPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
        });
        return branchByPage;

    }

    /**
     * 推广钱包支出汇总
     *
     * @param
     * @return
     */
    @Override
    public Map<String, Object> getBranchPromoteByPageCount(MemberExpenditureVo memberExpenditureVo) {
        QueryWrapper<MemberExpenditureVo> queryWrapper = Wrappers.query();
        // 订单类型
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStart())) {
            switch (memberExpenditureVo.getStart()) {
                case "TRANSFER":
                    list.add("TRANSFER"); // 转账
                    break;
                case "OFFLINE":
                    list.add("OFFLINE"); // 线下订单
                    break;
                case "NORMAL":
                    list.add("NORMAL"); // 线上订单
                    break;
                case "VIRTUAL":
                    list.add("VIRTUAL"); // 虚拟订单
                case "WITHDRAWAL":
                    list.add("WITHDRAWAL"); // 提现
                    break;
            }
        }
        queryWrapper.in(list != null && list.size() > 0, "a.expenditureType", list);
        // //除了未付款和已取消全查出来
        // List listNot = new ArrayList();
        // listNot.add("UNPAID");//未付款
        // listNot.add("CANCELLED");//已取消
        // queryWrapper.notIn("e.orderStatus", listNot);
        // 时间查询
        if (StringUtils.isNotEmpty(memberExpenditureVo.getStartDate())
                && StringUtils.isNotEmpty(memberExpenditureVo.getEndDate())) {
            queryWrapper.le("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
            queryWrapper.ge("DATE_FORMAT(a.expenditureTime,'%Y-%m-%d')", memberExpenditureVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(memberExpenditureVo.getMemberId())) { // 查询其中一个用户的
            queryWrapper.eq("a.payer", memberExpenditureVo.getMemberId());
        }
        queryWrapper.orderByDesc("a.expenditureTime");

        queryWrapper.eq(StringUtils.isNotEmpty(memberExpenditureVo.getOwner()), "a.owner",
                memberExpenditureVo.getOwner());
        queryWrapper.groupBy("a.receivableNo");
        Map branchByPage = baseMapper.getBranchPromoteByPageCount(queryWrapper);
        return branchByPage;
    }

    @Override
    public List<Member> getAgents(String agentMemberId) {
        // 查询合伙人表是否是代理商角色
        List memberIds = new ArrayList();
        Member member = this.baseMapper.selectById(agentMemberId);
        List<Partner> list = partnerService
                .list(new QueryWrapper<Partner>().eq("member_id", agentMemberId).eq("delete_flag", false));
        if (list.size() > 0) {
            String promotionCode = member.getPromotionCode(); // 获取代理商的推广码
            // 被城代理商推广的人
            List<Extension> extensions = eextensionService
                    .list(new QueryWrapper<Extension>().eq("extension", promotionCode).eq("delete_flag", false));
            extensions.forEach(item -> {
                memberIds.add(item.getMemberId());
            });
        }
        if (memberIds.size() == 0) {
            return new ArrayList<Member>();
        }
        // 查询城市合伙人推广的事业合伙人
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.in("a.member_id", memberIds).eq("a.delete_flag", false).eq("a.partner_type", "1")
                .eq("b.delete_flag", false);
        List<Member> shiYe = baseMapper.getShiYe(memberQueryWrapper);
        List promotionCodeList = new ArrayList(); // 事业所有的推广码
        shiYe.forEach(membe -> {
            promotionCodeList.add(membe.getPromotionCode());
        });
        if (promotionCodeList.size() > 0) {
            List<Extension> extensions = eextensionService
                    .list(new QueryWrapper<Extension>().in("extension", promotionCodeList).eq("delete_flag", false));
            extensions.forEach(e -> {
                memberIds.add(e.getMemberId());
            });
        }
        // 查询被推广的所有人
        List<Member> members = this.list(new QueryWrapper<Member>().in("id", memberIds).eq("delete_flag", false));
        return members;
    }

    @Override
    public IPage<MemberVO> getMemberListPage(MemberSearchVO memberSearchVO, PageVO page) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        AuthUser currentUser = UserContext.getCurrentUser();
        // 如果当前会员不为空，且为代理商角色
        if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
            AdminUser adminUser = adminUserService.getById(currentUser.getId());
            if (null != adminUser && StringUtils.isNotEmpty(adminUser.getRegionId())) {
                queryWrapper.in("a.location", regionService.getItemAdCod(adminUser.getRegionId()));
                // queryWrapper.in("a.location",
                // regionService.getPartnerAdCode(memberSearchVO.getAdcode(), "4"));
            }
        }
        if (memberSearchVO.getBeginTime() != null && memberSearchVO.getEndTime() != null) {
            queryWrapper.between("b.end_time", memberSearchVO.getBeginTime(), memberSearchVO.getEndTime());
        }

        // 推广人姓名
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getNameExte()), "m1.real_name", memberSearchVO.getNameExte());
        // 推广人电话
        queryWrapper.like(StringUtils.isNotEmpty(memberSearchVO.getMobileExte()), "m1.mobile", memberSearchVO.getMobileExte());

        // 获取区域下的所有地区
        if (StringUtils.isNotEmpty(memberSearchVO.getRegionId())) {
            List itemAdCod = regionService.getItemAdCod(memberSearchVO.getRegionId());
            queryWrapper.in("a.location", itemAdCod);
        }
        // 会员等级
        queryWrapper.eq(CharSequenceUtil.isNotBlank(memberSearchVO.getLevel()), "m.level", memberSearchVO.getLevel());
        // 按照电话号码查询
        queryWrapper.like(CharSequenceUtil.isNotBlank(memberSearchVO.getMobile()), "a.mobile",
                memberSearchVO.getMobile());
        // 查询
        queryWrapper.and(wrapper -> wrapper.isNull("b.owner").or().like("b.owner", "BUYER"));
        queryWrapper.eq("a.have_store", 0);
        queryWrapper.eq("a.delete_flag", 0);
        queryWrapper.eq("a.disabled", 1);
        queryWrapper.apply("a.id not in (SELECT DISTINCT member_id from li_partner where partner_type in ('1','2','4') and partner_state = 0 and delete_flag = 0 and audit_state = 'PASS')");
        queryWrapper.groupBy("a.id");
        // queryWrapper.and(wrapper ->
        // wrapper.isNull("p.audit_state").or().ne("p.audit_state", "PASS"));
        queryWrapper.orderByDesc("a.create_time");
        IPage<MemberVO> memberVOIPage = this.baseMapper.pageByCmember(PageUtil.initPage(page), queryWrapper);
        // 根据ad_code查询区域
        memberVOIPage.getRecords().forEach(item -> {
            item.setLocationName(regionService.getItemAdCodOrName(item.getLocation()));
            if (item.getPromoteMoney() != null)
                item.setPromoteMoney(
                        BigDecimal.valueOf(item.getPromoteMoney()).setScale(2, RoundingMode.DOWN).doubleValue());
            if (item.getRechargeMoney() != null)
                item.setRechargeMoney(
                        BigDecimal.valueOf(item.getRechargeMoney()).setScale(2, RoundingMode.DOWN).doubleValue());
        });
        return memberVOIPage;
    }

    @Override
    public IPage<RegionDetailVO> getRegionDetailList(RegionDetailVO regionDetailVO, PageVO page) {
        QueryWrapper<RegionDetailVO> queryWrapper = Wrappers.query();
        queryWrapper.eq("member_id", regionDetailVO.getMemberId());
        queryWrapper.eq("delete_flag", 0);
        IPage<RegionDetailVO> memberVOIPage = regionDetailMapper.getRegionDetailList(PageUtil.initPage(page),
                queryWrapper);
        return memberVOIPage;
    }
}
